rawmodel / framework

Strongly-typed JavaScript object with support for validation and error handling.
https://rawmodel.github.io/framework/
MIT License
142 stars 16 forks source link

Populate and serialize redused set of fields #88

Closed apapacy closed 3 years ago

apapacy commented 3 years ago

I want to use your library as odm for arangodb. But for that, it is necessary that patch requests do not initialize the missing fields to null. That is, it must be either an additional parameter to populate, serialize, or new methods with a reduced set of fields.

xpepermint commented 3 years ago

There are two options.

  1. You can define a custom patch() { ... } method that first builds a data object based on model.isChanged(); and then performs the update.

  2. (preferred) You load the record, apply changes and perform the update. This is usually the common practice since you wanna perform the validate action before the object is stored in the database. Also, this approach is the desired approach when working with ArangoDB to handle the atomicity right (it's different from e.g. MongoDB).

// Example:
async function mySampleRoute(req, res) {
 const { context, body } = req;
  const account = await new Account({}, { context });

  account.populateById(params.accountId); // your custom method to load the record
  if (!account.isPersistent()) {
    throw new Error("Account not found!");
  }

  try {
    account.populate(body); // patch data
    await account.validate(); // validate data before saving
    await account.save(); // custom method that saves data to DB
  } catch (err) {
    await account.handle(err);
  }
  if (account.isValid()) {
    return res.respond(200, account.serialize()); // respond with OK
  } else {
    throw new ValidationError(account); // respond with ERR
  }
}