graphiti-api / spraypaint.js

Graphiti Client / Javascript ORM / JSONAPI
MIT License
107 stars 69 forks source link

How to preload an instance without making a network request? #85

Closed LouisRitchie closed 3 years ago

LouisRitchie commented 3 years ago

Hello,

Suppose I use Spraypaint in a React app that is SSR'd. In responding to a request, the frontend server fetches data & instantiates models using Spraypaint/Graphiti layer and, after generating markup, sends markup and data to the client.

The data is a JSON representation of up-to-date models. How can I instantiate those models on the client without making a network request?

I believe I should use middleware to do this, and some methods from the library that are exposed to us.

This looked relevant: https://github.com/graphiti-api/spraypaint.js/issues/79

Big apology if this is obvious, I've always struggled with Spraypaint because I come from a node background and not a RoR background.

LouisRitchie commented 3 years ago

My question comes down to initizializing a set of Spraypaint models with data retrieved from a javascript object or JSON. In my case, I'm setting a global variable containing my initial data using <script>var init = ${JSON.stringify(data)}</script> inserted into the markup.

I would gladly send the internal state of spraypaint state along the wire, with instantiated models included, but something tells me that's not how it works!

Reizar commented 3 years ago

@LouisRitchie I'm still new to using Spraypaint so there might be a better way of doing this, but Spraypaint models can accept an object with their attributes to initialize them.

So you should be able to do something along these lines:

var init = ${JSON.stringify(data)}
// Assuming init is an Array of objects
const models = init.map((attributes) => {
  const model = new ModelName(attributes)
  model.isPersisted = true
  return model
})

The isPersisted flag makes sure SprayPaint knows it's already been saved in the backend, and will issue PUT requests whenever you call .save() rather than POST's.

Hope this helps.

richmolj commented 3 years ago

Absolutely right @Reizar ! @LouisRitchie check out the tests to see this all over the place.

LouisRitchie commented 3 years ago

Thanks guys I appreciate this a lot.