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

@sequelize-graphql/core

v1.4.12

Published

Lightweight library to sync sequelize and graphql

Downloads

409

Readme

sequelize-graphql

NPM Version GitHub Actions Workflow Status GitHub Release Date - Published_At

Opinionated zero dependency library to sync Sequelize and GraphQL.

[!WARNING] The library is in WIP until v2 is released. Issues and PRs are welcomed.

Key features

  • [x] Define your model in one place and have the Sequelize model as well as the GraphQL type auto-generated.
  • [x] GraphQL oriented (e.g A model must have a primary key named id wich is by default a UUID mapped to a GraphQLID).
  • [x] Association handling (e.g An hasMany association will be exposed as a pagination).
  • [x] Pagination utility which is orderable, filterable, and type safe.
  • [x] N+1 query handling. Caching and batching is automatically handled.
  • [x] Enums handling.
  • [x] Sequelize utilities.
  • [x] GraphQL utilities.

Getting Started

Install sequelize-graphql from npm

With npm:

npm install --save @sequelize-graphql/core sequelize graphql dataloader

or using yarn:

yarn add @sequelize-graphql/core sequelize graphql dataloader

See Peer dependencies breakdown for more information.

Setup the context and you are good to go:

import { makeContext } from '@sequelize-graphql/core';

// Apollo Server example
const { url } = await startStandaloneServer(server, {
  context: async ({ req, res }) => ({
    ...makeContext(), // An object containing everyting sequelize-graphql needs to work properly.
    authToken: req.headers.authorization, // Stuff you want to place in the context like an auth token.
  }),
});

Usage

One can easily define a model like so:

import type { ForeignKey } from 'sequelize';
import type { IdType, InferModelAttributesWithDefaults } from '@sequelize-graphql/core';

import { GraphQLNonNull, GraphQLString } from 'graphql';
import { Model, STRING, ID, ENUM } from '@sequelize-graphql/core';
import sequelize from '@db/index';
import { Author, Rating } from '@models/index';

export enum Genre {
  Action = 'Action',
  Fantasy = 'Fantasy',
  Horror = 'Horror',
}

export const GenreEnum = ENUM({ name: 'Genre', values: Genre });

export interface BookModel extends InferModelAttributesWithDefaults<BookModel> {
  title: string;
  genre: Genre;

  authorId: ForeignKey<IdType>; // Auto-added by the belongsTo association
}

const Book: Model<BookModel> = new Model({
  name: 'Book',
  columns: {
    title: { type: STRING, allowNull: false, exposed: true },
    genre: { type: GenreEnum, defaultValue: Genre.Action, exposed: true },
  },
  fields: {
    fullTitle: {
      type: new GraphQLNonNull(GraphQLString),
      async resolve(book, args, ctx) {
        const { authorId, title } = book;
        const author = await Author.ensureExistence(authorId, { ctx });
        return `${title} by ${author.name}`;
      },
    },
  },
  associations: () => ({
    author: {
      model: Author,
      type: 'belongsTo',
      exposed: true,
    },

    ratings: {
      model: Rating,
      type: 'hasMany',
      exposed: true,
    },
  }),
  timestamps: true,
  sequelize,
});

Here is the GraphQL type that will be generated:

type Book {
  id: ID!
  createdAt: Date!
  updatedAt: Date!
  title: String!
  genre: Genre
  author: Author
  ratings(offset: Int, limit: Int, order: [RatingOrderBy!], filters: RatingFilters): RatingOffsetConnection!
  fullTitle: String!
}

The lib comes with a set of utilities to generate queries and mutations for your models.
Query:

export default new GraphQLObjectType({
  name: 'Query',
  fields: {
    ...exposeModel(Book, {
      findById: 'book',
      findByIds: false,
      pagination: 'books',
    }),
  }
});
type Query {
  book(id: ID!): Book!
  books(offset: Int, limit: Int, order: [BookOrderBy!], filters: BookFilters): BookOffsetConnection!
}

Mutation:

import { GraphQLID, GraphQLNonNull, GraphQLString } from 'graphql';
import { genModelMutations } from '@sequelize-graphql/core';
import { Book, Author, GenreEnum } from '@models/index';

export default genModelMutations(Book, {
  create: {
    args: {
      authorId: { type: new GraphQLNonNull(GraphQLID) },
      title: { type: new GraphQLNonNull(GraphQLString) },
      genre: { type: new GraphQLNonNull(GenreEnum.gqlType) },
    },
    async resolve(_, args, ctx) {
      const { authorId, title, genre } = args;
      await Author.ensureExistence(authorId, { ctx });
      return Book.model.create({ authorId, title, genre });
    },
  },

  update: {
    args: {
      title: { type: GraphQLString },
      genre: { type: GenreEnum.gqlType },
    },
    async resolve(book, args, ctx) {
      const { title, genre } = args;
      return book.update({ title, genre });
    },
  },

  delete: true,
});
type BookMutation {
  create(input: BookCreateInput!): Book!
  update(id: ID!, input: BookUpdateInput!): Book!
  delete(id: ID!): Boolean!
}

Example

A simple project running sequelize-graphql:
https://github.com/BaptisteMartinet/sequelize-graphql-example