holidayextras / jsonapi-server

A config driven NodeJS framework implementing json:api and GraphQL
MIT License
488 stars 115 forks source link

Creating new resource with relationship triggers related resource's beforeCreate method #290

Open cahva opened 7 years ago

cahva commented 7 years ago

First of all, I want to thank you guys for great work! Now to the issue I'm having..

I have 2 resources users and apikeys:

users

handlers: authenticationHandler.chain(userHandler).chain(mongoStoreHandler),
attributes: {
  ...
  password: jsonApi.Joi.string().min(6).strip()
    .description("User's password"),
  apikeys: jsonApi.Joi.many('apikeys')
    .description('Apikeys belonging to user')
}

It has userHandler chained where I turn user's password to hash in beforeCreate and beforeUpdate.

apikeys

handlers: authenticationHandler.chain(mongoStoreHandler),
attributes: {
  name: jsonApi.Joi.string().required()
    .description('Apikey name')
    .example('My example api-key'),
  user: jsonApi.Joi.one('users')
    .description('Apikey user')
}

Now when I want to create a new apikey for the user, I send the request (a user with that id already exists):

POST /api/apikeys

{
  "data": {
    "type": "apikeys",
    "attributes": {
      "name": "My apikey"
    },
    "relationships": {
      "user": {
        "data": {
          "type": "users",
          "id": "8a6f0195-d5a7-41f3-892c-51dbc5216db7"
        }
      }
    }
  }
}

When doing that request I think it should not trigger userHandlers beforeCreate method at all but it does!

userHandler

const jsonApi = require('jsonapi-server');

const userHandler = new jsonApi.ChainHandler();

userHandler.beforeCreate = (request, newResource, callback) => {
  console.log('beforeCreate from userHandler', newResource.type);
 ...
}

That will output this to console: beforeCreate from userHandler apikeys.

So is this a bug or have I misunderstood something fundamental how chainhandlers work? :)

For now, I just added a check for the newResource.type so it goes through if the type is something else than "users".

todoesverso commented 7 years ago

I am having the same issue.

Basically if using require/import of a chain handler, then any resource using a chain handler will go thru all existing handlers.

It definitly looks like a critical issue to me.