Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-sequelize-generator

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-sequelize-generator

A set of tools to easily generate a Graphql API from sequelize models.

  • 3.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
36
decreased by-21.74%
Maintainers
1
Weekly downloads
 
Created
Source

Graphql Sequelize Generator

Conventional Commits Build Status

API | FAQ | Contributing

Graphql-Sequelize-Generator (GSG) is a set of tools that will allow you to easily generate a graphql API from your sequelize models.

What can I do?

The tools provided by this library will allow you to:

  • Query any model defined in your app through Graphql.
  • Auto-generate create/update/delete mutations.
  • Define before/after hooks and all resolvers, including the mutations.
  • Easily create custom mutations.
  • Get an integrated interface to test your Graphql API: Graphqli is available by default.
  • Counts for each model can also be generated
  • Subscriptions auto-generated for mutations
  • Add custom fields/resolvers on auto-generated types

Generated API

Getting Started

Installation

To use GSG in your project, run:

yarn add graphql-sequelize-generator
# or "npm i --save graphql-sequelize-generator"

Usage

Caution: GSG requires at least Node v9.11.2 or greater as it is using async/await.

Example - adding a GraphQL API to my express:

const express = require("express");
const {
  generateModelTypes,
  generateGraphqlExpressMiddleware
} = require("graphql-sequelize-generator");
const models = require("./models");

const types = generateModelTypes(models);

graphqlSchemaDeclaration.user = {
  model: models.user,
  actions: ["list", "create"]
};

const server = generateApolloServer({
  graphqlSchemaDeclaration,
  types,
  models
});

const app = express();
server.applyMiddleware({
  app,
  path: "/graphql"
});

Example - Add a custom mutation related to a model.

graphqlSchemaDeclaration.user = {
  model: models.user,
  actions: ["list", "create"],
  additionalMutations: {
    serverStatistics = {
      type: new GraphQLObjectType({
        name: "serverStatistics",
        description: "Statistics about the server",
        fields: {
          serverBootDate: { type: GraphQLString }
        }
      }),
      resolve: async (source, args, context, info) => {
        return {
          serverBootDate: context.bootDate
        };
      }
    }
  }
}

Example - Select only configuration

graphqlSchemaDeclaration.user = {
  model: models.user,
  actions: ["list"] // Other available options: ['list', 'create', 'update', 'delete', 'count']
};

Example queries - Query associations

{
  company(order: "reverse:name", limit: 50) {
    id
    name
    departments {
      id
      users {
        id
        name
      }
    }
  }
  serverStatistics {
    serverBootDate
  }
}

Example configuration - All options:

const server = generateApolloServer({
  graphqlSchemaDeclaration,
  types,
  models,
  customMutations: {
    /* ...
      your custom mutations that are not related to any declared models.
     ... */
  },
  // Apollo server options can be passed here.
  apolloServerOptions: {
    playground: true,
    context: addDataloaderContext,
    extensions: [
      () => new ApolloNewrelicExtension(),
      () => new ErrorTrackingExtension()
    ],
    tracing: true,
    // Example of socket security hook.
    subscriptions: {
      path: '/api/graphql',
      onConnect: async (connectionParams, webSocket) => {
        return getSubscriptionAccountAndUserFromJWT(connectionParams)
      }
    }
  },
  pubSubInstance
})
);

You can check the [test schema](examples which contains all of the feature available in the library.

API Documentation

Explore the API documentation and examples to learn more.

Known limitations

One thing that makes this library possible is dataloader sequelize. Those limitations are so inherited:

Only plain requests are batched, meaning requests with includes and transactions are skipped. The batching does handle limit, and where but different limits and wheres are placed in different batches. Currently this module only leverages the batching functionality from dataloader, caching is disabled.

It will mostly impact you if you try to inject tables in the include property through the before hook.

For example when trying to limit the listing of companies:

Instead of that:

list: {
  before: async (findOptions, args, context) => {
    if (typeof findOptions.include === "undefined") {
      findOptions.include = [];
    }
    findOptions.include.push({
      model: models.user,
      where: {
        id: context.myUserId
      }
    });
    return findOptions;
  };
}

Try to do this if possible:

list: {
  before: async (findOptions, args, context) => {
    if (typeof findOptions.where === "undefined") {
      findOptions.where = {};
    }
    findOptions.where = {
      $and: [findOptions.where, { id: context.myAllowedCompaniesIds }]
    };
    return findOptions;
  };
}

Contributing to GSG

Check out contributing guide to get an overview of open-source development at Matters.

Tests can be run with:

yarn test

A test server can be started with generated seeds with:

yarn start

It will make available a Graphiql interface at this url

FAQ

Q: Can I hide fields?

This is available through this configuration:.

@todo: Add an example

Keywords

FAQs

Package last updated on 08 Jul 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc