Skip to content

Instantly share code, notes, and snippets.

@tajidyakub
Created March 1, 2018 14:07
Show Gist options
  • Save tajidyakub/f0dfa936773db48cb5df2e1bc46778c8 to your computer and use it in GitHub Desktop.
Save tajidyakub/f0dfa936773db48cb5df2e1bc46778c8 to your computer and use it in GitHub Desktop.
Feathersjs hook to get Gravatar URL based on user's email Address

These hooks executed in order, by assumption users and profiles are separated.

(after)Create User-->(before)Create Profiles

After Create User Hook create-profile.js

module.exports = function (options = {}) {
  return async context => {
    async function patchProfile (userId, data) {
      return await context.service.patch(userId, data);
    }
    const userId = context.result._id,
      email = context.result.email,
      profiles = context.app.service('profiles'),
      data = { userId: userId },
      params = { email: email };
      
    await profiles.create(data,params).then((result) => {
          const data = { profileId: result._id };
          patchProfile(userId, data);
      });
      
    return context;
  };
};

Before creating profile hook gravatar-url.js This hook require crypto for hashing npm i --save crypto

const crypto = require('crypto'),
  gravatarUrl = 'https://s.gravatar.com/avatar',
  query = 's=64';

// eslint-disable-next-line no-unused-vars
module.exports = function (options = {}) {
  return async context => {
    const { email } = context.params, 
      hash = crypto.createHash('md5').update(email).digest('hex');
    context.data.avatarUrl = `${gravatarUrl}/${hash}?${query}`;
    
    return context;
  };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment