Search code examples
node.jsfeathersjs

Change JSON response for registering a user


How can I create a hook in FeathersJS that returns the JWT token with the user object in the JSON response after the user is created in the users service?

I've tried in users.hooks.js:

 after: {
        all: [
            // Make sure the password field is never sent to the client
            // Always must be the last hook
            protect('password')
        ],
        find: [],
        get: [],
        create: [
            function(hook) {
                const data = {
                    email: hook.data.email,
                    password: hook.data.password,
                    strategy: 'local'
                };

                return hook.app.service('authentication').create(data).then(page => {
                    page.user = hook.result;
                    hook.result = page;
                    return Promise.resolve(hook);
                });
            }
        ],
        update: [],
        patch: [],
        remove: []
    },

But the JSON response stays the same. Is it possible to edit the FeathersJS authentication modules?


Solution

  • I've had a similar issue when trying to manipulate context.result (hook.result in your case. You should name it context though).

    In my understanding, the hook.result is a reference to the actual object that gets returned from the service. So, you can manipulate that object as you please.

    However in your case, you didn't change the actual result object, you took another object - page, manipulated it, then changed hook.result to reference that new object page. The actual result that hasn't changed.

    hook.result = page;
    

    The line above is your mistake. What you should do is:

    hook.result.accessToken = page.accessToken

    That way you manipulate the actual response object.

    I would write your the function like this:

     async function (context) {
         const data = {
             email: context.data.email,
             password: context.data.password,
             strategy: 'local'
          };
    
          const auth = await context.app.service('authentication').create(data);
    
          context.result.accessToken = auth.accessToken;
    
          return context;
     }
    

    The response JSON would then have the accessToken property on it.