npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

hapi-sequelize-dynamic-fields

v1.1.0

Published

Dynamic fields for query

Downloads

27

Readme

Hapi-sequelize-dynamic-fields

Build Status js-semistandard-style

Sometimes we return values at a given endpoint that not always we need all the information, with the plugin you can go through the header which fields you want to return.

For example, we have a model of Tasks (sequelize) that has a relationship for the user. In this way, we could structurer the following query sequelize:

const options = {
  attributes: ['id', 'descriptions', 'observation'],
  include: [{
    model: request.database.User,
    attributes: ['id', 'username', 'lastname', 'email']
  }]
};

In this case, all the fields entered in the attributes properties will be returned, including to the related table. But, will all this information always be used?

We can do in the following manner:

model.findAndCountAll(request.fieldsAll(options));

The plugin provide a call , request.fieldsAll, in which checks if there a property in the header called fields, if there is, the query will be mounted according to the fields informed, in case the field there isn’t, an exception will be thrown AttributesInvalidError.

In the return of our request we can inform which fields are permitted, by the function request.fieldsHeaders, for example:

return reply(values).header('allowing-fields', request.fieldsHeaders(options));

Response Headers:

"allowing-fields": "id,descriptions,observation,User.id,User.username,User.firstName,User.lastName,User.email",

##Example:

####Configuration Hapijs and K7

const Hapi = require('hapi');
const path = require('path');

let server = new Hapi.Server();

const dir = path.join(__dirname, '/models/**.js');

const register = [{
  register: require('k7'),
  options: {
    models: dir,
    adapter: require('k7-sequelize'),
    connectionOptions: {
      options: {
        dialect: 'sqlite'
      }
    }
  }
}, {
  register: require('hapi-sequelize-dynamic-fields')
}];

server.register(register, (err) => {
  if (err) throw err;
});

server.connection();

####Create models

  const User = sequelize.define('User', {
    username: {
      type: DataType.STRING(40),
      allowNull: false,
      unique: true
    },
    firstName: {
      type: DataType.STRING(100),
      allowNull: false,
      field: 'first_name'
    },
    lastName: {
      type: DataType.STRING(50),
      allowNull: false,
      field: 'last_name'
    },
    email: {
      type: DataType.STRING(120),
      allowNull: false,
      unique: true,
      validate: {
        isEmail: true
      }
    },
    password: {
      type: DataType.STRING(200),
      allowNull: false
    }
  }, {
    createdAt: 'created_at',
    updatedAt: 'update_at',
    tableName: 'users'
  });

  const Tasks = sequelize.define('Tasks', {
    descriptions: {
      type: DataType.STRING(200),
      allowNull: false,
      unique: true
    },
    observation: {
      type: DataType.STRING(100),
      allowNull: false
    },
    userId: {
      type: DataType.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      },
      field: 'user_id'
    }
  }, {
    createdAt: 'created_at',
    updatedAt: 'update_at',
    tableName: 'tasks',

    classMethods: {
      associate: (models) => {
        Tasks.belongsTo(models.User, {
          foreignKey: 'userId'
        });
      }
    }
  });

####Create routes

...
 server.route([
    {
      method: 'GET',
      path: '/user',
      config: {
        handler: Controller.list
      }
    },
    {
      method: 'GET',
      path: '/tasks',
      config: {
        handler: Controller.listTasks
      }
    }
  ]);
...    

####Create controllers

export const list = async (request, reply) => {
  try {
    const model = request.database.User;

    const options = {
      attributes: ['id', 'username', 'lastname', 'email'],
    };

    const values = await model.findAndCountAll(request.fieldsAll(options));

    return reply(values).header('allowing-fields', request.fieldsHeaders(options));
  } catch (err) {
    return reply.badImplementation(err);
  }
};

export const listTasks = async (request, reply) => {
  try {
    const model = request.database.Tasks;

    const options = {
      attributes: ['id', 'descriptions', 'observation'],
      include: [{
        model: request.database.User,
        attributes: ['id', 'username', 'lastname', 'email']
      }]
    };

    const values = await model.findAndCountAll(request.fieldsAll(options));

    return reply(values).header('allowing-fields', request.fieldsHeaders(options));
  } catch (err) {
    return reply.badImplementation(err);
  }
};

###Example Users

####request

curl -X GET --header 'Accept: application/json' --header 'fields: id' 'http://localhost:3000/user'

####SQL

SELECT 'id' FROM 'users' AS 'User';

####request

curl -X GET --header 'Accept: application/json' --header 'fields: id, email' 'http://localhost:3000/user'

####SQL

SELECT 'id', 'email' FROM 'users' AS 'User';

####Response Headers { "allowing-fields": "username,firstName,lastName,email", ... }

###Example Tasks

curl -X GET --header 'Accept: application/json' 'http://localhost:3000/tasks'

####SQL

SELECT 
	'Tasks'.'id', 
	'Tasks'.'descriptions', 
	'Tasks'.'observation', 
	'User'.'id' AS 'User.id', 
	'User'.'username' AS 'User.username', 
	'User'.'first_name' AS 'User.firstName', 
	'User'.'last_name' AS 'User.lastName', 
	'User'.'email' AS 'User.email' 
FROM 'tasks' AS 'Tasks' 
LEFT OUTER JOIN 'users' AS 'User' ON 'Tasks'.'user_id' = 'User'.'id';

===

curl -X GET --header 'Accept: application/json' --header 'fields: id, User.id, User.username' 'http://localhost:3000/tasks'

####SQL

SELECT 
	'Tasks'.'id', 
	'User'.'id' AS 'User.id', 
	'User'.'username' AS 'User.username' 
FROM 'tasks' AS 'Tasks' 
LEFT OUTER JOIN 'users' AS 'User' ON 'Tasks'.'user_id' = 'User'.'id';

####Response Headers { "allowing-fields": "id,descriptions,observation,User.id,User.username,User.firstName,User.lastName,User.email", ... }