0

I have an API developed with Serverless and serverless-offline which is deployed to AWS Lambda. Objection/Knex is used for DB, Firebase for authentication, and Middy to manage the requests.

For the logged-in users, I'm trying to:

  1. Automatically add the company ID on inserting to DB
  2. Exit if a user tries to update or delete an entry that belongs to another company

As of now, this is manually checked. I'm trying to figure out if this can be built into the Model so that it can be eliminated from the main code.

The company ID is available in the event and it's possible to exit the process from the static beforeInsert method. Is it possible to pass data from the event to the model?

Handler:

const baseHandler = async (event) => {

  const companyId = event?.requestContext?.authorizer?.claims?.companyId;

  await event.models.Client.query().insert({
    name: event?.body?.name || "",
    companyId // This is the current method. I need to eliminate this
  });

  
  await event.models.Client.query().where('id', 'uuid').where('companyId', companyId).update({
    name: event?.body?.name || "",
  }); // Need to remove the check for companyId from here, and add it to the Model

};

const endpoint = middy(baseHandler)
  .use(jsonBodyParser())
  .use(validator({ eventSchema }))
  .use(httpErrorHandler())
  .use(useModels());

Model:


module.exports = class Client extends Model {
  
  async $beforeInsert(queryContext) {
    this.companyId = '' // Set the company ID from the logged in user
  }

  static beforeInsert(args) {
    if (!belongsToUser) { // This is what I was trying
      args.cancelQuery();
    }
  }

  static get tableName() {
    return "clients";
  }
};

Mahesh Samudra
  • 1,039
  • 1
  • 11
  • 25

0 Answers0