All Projects → almost-full-stack → graphcraft

almost-full-stack / graphcraft

Licence: MIT license
Rapildy build and extend GraphQL API based on Sequelize models. This library helps you focus on business logic while taking care of GraphQL schema automatically.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to graphcraft

sequelize-embed
Easily insert and update sequelize models with deeply nested associations
Stars: ✭ 15 (-70%)
Mutual labels:  sequelize, sequelize-models
graphql-resolver-cache
Caching for Graphql Resolvers
Stars: ✭ 18 (-64%)
Mutual labels:  graphql-js
node-express-clean-architecture
A modular folder structure for developing highly scalable and maintainable APIs in nodejs using express.
Stars: ✭ 41 (-18%)
Mutual labels:  sequelize
sequelize-sscce
Base repository for creating and sharing Sequelize SSCCEs
Stars: ✭ 32 (-36%)
Mutual labels:  sequelize
sequelize-db-export-import
Generater models from mysql db or import tables from models files
Stars: ✭ 26 (-48%)
Mutual labels:  sequelize
rest-api-node-typescript
This is a simple REST API with node and express with typescript
Stars: ✭ 154 (+208%)
Mutual labels:  sequelize
nodejs-integration-testing
Integration testing of a Node.js / Express.js / Sequelize app
Stars: ✭ 23 (-54%)
Mutual labels:  sequelize
my-blog
node.js vue.js nuxt.js hapi.js mysql 仿简书博客
Stars: ✭ 25 (-50%)
Mutual labels:  sequelize
graphql-spotify
GraphQL Schema And Resolvers For Spotify Web API
Stars: ✭ 55 (+10%)
Mutual labels:  graphql-js
sequelize-slugify
Sequelize Slugify is a plugin for the Sequelize ORM that automatically creates and updates unique, URL safe slugs for your database models.
Stars: ✭ 49 (-2%)
Mutual labels:  sequelize
Project04-C-Whale
🐋할고래Do - Whale 확장 앱 API를 이용한 할일관리 웹, 앱 서비스
Stars: ✭ 26 (-48%)
Mutual labels:  sequelize
mall-by-react
一个react商城客户端和egg服务端
Stars: ✭ 22 (-56%)
Mutual labels:  sequelize
typescript-orm-benchmark
⚖️ ORM benchmarking for Node.js applications written in TypeScript
Stars: ✭ 106 (+112%)
Mutual labels:  sequelize
node-sequelize
nodejs使用sequelize的api测试应用
Stars: ✭ 29 (-42%)
Mutual labels:  sequelize
wily
Build Node.js APIs from the command line (Dead Project 😵)
Stars: ✭ 14 (-72%)
Mutual labels:  sequelize
graphql-sequelize-generator
A Graphql API generator based on Sequelize.
Stars: ✭ 20 (-60%)
Mutual labels:  sequelize
sequelize-paper-trail
Sequelize plugin for tracking revision history of model instances.
Stars: ✭ 90 (+80%)
Mutual labels:  sequelize
masterclass-nodejs-sql
Código produzido durante o vídeo "Masterclass #01 - SQL no Node.js com Sequelize" no Youtube 🔥
Stars: ✭ 156 (+212%)
Mutual labels:  sequelize
todo-list
A practical web application built with Node.js, Express, and MySQL for you to readily record, view, and manage your tasks with an account: Create, view, edit, delete, filter, and sort expenses are as easy as pie 🥧
Stars: ✭ 18 (-64%)
Mutual labels:  sequelize
dhiwise-nodejs
DhiWise Node.js API generator allows you to instantly generate secure REST APIs. Just supply your database schema to DhiWise, and a fully documented CRUD APIs will be ready for consumption in a few simple clicks. The generated code is clean, scalable, and customizable.
Stars: ✭ 224 (+348%)
Mutual labels:  sequelize

GraphCraft

This repository and package is renamed to graphcraft.

npm version dependencies devdependencies Build Status

Rapildy build and extend GraphQL API based on Sequelize models. This library helps you focus on business logic while taking care of GraphQL schema automatically. https://almost-full-stack.github.io/graphcraft/

If you are updating from a previous version to 1.0 read notes at the end to fix breaking changes it will cause.

Installation

npm install graphcraft

Prerequisites

This package assumes you have graphql and sequelize already installed (both packages are declared as peerDependencies).

This library uses two set of configurations, Library Options and Model Options.

Library Options

These options are defined globally and are applied throughout schema and all models.

/**
 * naming convention for mutations/queries and types.
 * {name} = Model Name or type name
 * {type} = Get | Create | Update | Delete
 * {bulk} = Bulk for bulk operations only
 * */
   
naming: {
  pascalCase: true, // applied everywhere, set to true if you want to use camelCase
  queries: '{name}{type}', // applied to auto generated queries
  mutations: '{name}{type}{bulk}', // applied to auto generated mutations
  input: '{name}', // applied to all input types
  rootQueries: 'RootQueries',
  rootMutations: 'RootMutations',
  // {type} and {bulk} will be replaced with one of the following
  type: {
    create: 'Create',
    update: 'Update',
    delete: 'Delete',
    restore: 'Restore',
    byPk: 'ByPK',
    get: '',
    bulk: 'Bulk',
    count: 'Count',
    default: 'Default'
  }
}
// default limit to be applied on find queries
limits: {
  default: 50, // default limit. use 0 for no limit
  max: 100, // maximum allowed limit. use 0 for unlimited
  nested: false // whether to apply these limits on nested/sub types or not
}
// nested objects can be passed and will be mutated automatically. Only hasMany and belongsTo relation supported.
nestedMutations: true, // doesn't work with add bulk mutation

/**
 * update modes when sending nested association objects
 * UPDATE_ONLY > update only incoming records
 * UPDATE_ADD > update existing records and add new ones i.e [{id: 1, name: 'test'}, {name: 'test2'}] record[0] will be updated and record[1] will be added
 * UPDATE_ADD_DELETE > not recommended: update existing records, add new ones and delete non-existent records i.e [{id: 1, name: 'test'}, {name: 'test2'}] record[0] will be updated, record[1] will be added, anything else will be deleted
 * MIXED > i.e [{id: 1, name: 'test'}, {id:2}, {name: 'test2'}], record[0] will be updated, record[1] will be deleted and record[2] will be added
 * IGNORE > ignore nested update
 */

nestedUpdateMode: 'MIXED',
// applied globaly on both auto-generated and custom queries/mutations.
// only specified queries/ and mutations would be exposed via api
exposeOnly: {
  queries: [],
  mutations: [],
  // instead of not generating queries/mutations this will instead throw an error.
  throw: false // string message
}
// these models will be excluded from graphql schema
exclude: [], // ['Product'] this will exclude all queries/mutations for Product model.
// include these arguments to all queries/mutations
includeArguments: {}, // {'scopeId': 'int'} this will add scopeId in arguments for all queries and mutations
// enabled/disable dataloader for nested queries
dataloader: false, // use dataloader for queries. Uses dataloader-sequelize
// mutations are run inside transactions. Transactions are accessible in extend hook.
transactionedMutations: true,
// generic or those types/queries/mutations which are not model specific
importTypes: {}, // use this to import other non-supported graphql types such as Upload or anyother
types: {}, // custom graphql types
queries: {}, // custom queries
mutations: {}, // custom mutations
// global hooks, behaves same way as model before/extend
globalHooks: {
  before: {}, // will be executed before all auto-generated mutations/queries (fetch/create/update/destroy)
  extend: {} // will be executed after all auto-generated mutations/queries (fetch/create/update/destroy)
},
findOneQueries: false, // create a find one query for each model (i.e. ProductByPk), which takes primary key (i.e. id) as argument and returns one item. Can also pass an array of models to create for specific models only (i.e. ['Product', 'Image'])
fetchDeleted: false, // Globally when using queries, this will allow to fetch both deleted and undeleted records (works only when tables have paranoid option enabled)
restoreDeleted: false, // Applies globally, create restore endpoint for deleted records
// data, source, args, context, info are passed as function arguments
// executes after all queries/mutations
logger() {
  return Promise.resolve();
},
// your custom authorizer
// executes before all queries/mutations
authorizer() {
  return Promise.resolve();
},
// these error messages are used when certain exceptions are thrown
// must be used with errorHandler function exposed via library
errorHandler: {
  'ETIMEDOUT': { statusCode: 503 }
}
const options = {
  exclude: ["payments"],
  authorizer: function authorizer(source, args, context, info) {
    const { fieldName } = info; // resource name

    return Promise.resolve();
  }
};

const { generateSchema } = require("graphcraft")(options);

Model Options

Following options are model specific options, must be accessible via model.graphql property.

// manipulate your model attributes
attributes: {
// list attributes which are to be ignored in Model Input
  exclude: [], // ['id', 'createdAt'], these fields will be excluded from GraphQL Schema
// attributes in key:type format which are to be included in Model Input
  include: {}, // {'customKey': 'string'} this extra field will be added in GraphQL schema
},
// scope usage is highy recommended.
// common scope to be applied on all find/update/destroy operations
scopes: null, 
// 'scopes': ['scope', 'args.scopeId'] this will pass value of args.scopeId to model scope
// values can be either picked from args or context
// rename default queries/mutations to specified custom name
alias: {},
// {'fetch': 'productGet', 'create': 'productAdd', 'update': ..., 'destroy': ....}
bulk: { // OR bulk: ['create', 'destroy', ....]
  enabled: [], // enable bulk options ['create', 'destroy', 'update']
  // Use bulkColumn when using bulk option for 'create' and using returning true to increase efficiency.
  bulkColumn: false, // bulk identifier column, when bulk creating this column will be auto filled with a uuid and later used to fetch added records 'columnName' or ['columnName', true] when using a foreign key as bulk column
  returning: true // This will return all created/updated items, doesn't use sequelize returning option.
}
types: {}, // user defined custom types
mutations: {}, // user defined custom mutations
queries: {}, // user defined custom queries
// exclude one or more default mutations ['create', 'destroy', 'update']
excludeMutations: [],
excludeQueries: [], // exclude one or more default queries ['fetch']
// HOOKS
// each hook must return a promise.
// extend/after hook default queries/mutations behavior {fetch, create, destroy, update}
// (data, source, args, context, info) are passed to extend
extend: {},
// before hook for default queries/mutations behavior {fetch, create, destroy, update}
// (source, args, context, info) arguments are passed to before
before: {},
// overwrite default queries/mutations behavior {fetch, create, destroy, update}
// overwrite hooks are passed (source, args, context, info) arguments
overwrite: {},
joins: false // make a query using join (left/right/inner) instead of batch dataloader, join will appear in all subtype args. Right join won't work for sqlite
readonly: false, // exclude create/delete/update mutations automatically
fetchDeleted: false, // same as fetchDeleted as global except it lets you override global settings
restoreDeleted: false // same as restoreDeleted as global except it lets you override global settings
// define hooks to be invoked on find queries {before, after}
find: {}

Usage in Model

Product.graphql = {
    attributes: {
        exclude: ['description'],
        include: { modelPortfolioId: 'int', obj: 'myObj' },
    },
    ...REST_OF_OPTIONS
};

Usage

const {generateModelTypes, generateSchema} = require('graphcraft')(options);
const models = require('./models')
const schema = await generateSchema(models) // Generates the schema, return promise.

Example with Express

const { GraphQLSchema } = require('graphql');
const express = require('express');
const graphqlHTTP = require('express-graphql');

var options = {
  exclude: ["Users"]
}

const {generateSchema} = require('graphcraft')(options);

const models = require('./models');

const app = express();

app.use('/graphql', async (req, res) => {
  
  const schema = await generateSchema(models, req);

  return graphqlHTTP({
      schema: new GraphQLSchema(schema),
      graphiql: true
    })(req, res);

});

app.listen(8080, function() {
  console.log('RUNNING ON 8080. Graphiql http://localhost:8080/graphql')
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].