• Stars
    star
    382
  • Rank 112,241 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚠️ DEVELOPMENT DISCONTINUED - Mongoose (MongoDB) adapter for graffiti (Node.js GraphQL ORM)

⚠ Notice: the development of the package is discontinued. Use it for educational purposes and hobby projects only.

graffiti Mongoose

npm version CircleCI bitHound Overall Score Known Vulnerabilities

Mongoose (MongoDB) adapter for GraphQL.

graffiti-mongoose generates GraphQL types and schemas from your existing mongoose models, that's how simple it is. The generated schema is compatible with Relay.

For quick jump check out the Usage section.

Install

npm install graphql @risingstack/graffiti-mongoose  --save

Example

Check out the /example folder.

cd graffiti-mongoose
npm install # install dependencies in the main folder
cd example
npm install # install dependencies in the example folder
npm start # run the example application and open your browser: http://localhost:8080

Usage

This adapter is written in ES6 and ES7 with Babel but it's published as transpiled ES5 JavaScript code to npm, which means you don't need ES7 support in your application to run it.

Example queries can be found in the example folder.

usual mongoose model(s)
import mongoose from 'mongoose';

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    // field description
    description: 'the full name of the user'
  },
  hiddenField: {
    type: Date,
    default: Date.now,
    // the field is hidden, not available in GraphQL
    hidden: true
  },
  age: {
    type: Number,
    indexed: true
  },
  friends: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }]
});

const User = mongoose.model('User', UserSchema);
export default User;
graffiti-mongoose
import {getSchema} from '@risingstack/graffiti-mongoose';
import graphql from 'graphql';
import User from './User';

const options = {
  mutation: false, // mutation fields can be disabled
  allowMongoIDMutation: false // mutation of mongo _id can be enabled
};
const schema = getSchema([User], options);

const query = `{
    users(age: 28) {
      name
      friends(first: 2) {
        edges {
          cursor
          node {
            name
            age
          }
        }
        pageInfo {
          startCursor
          endCursor
          hasPreviousPage
          hasNextPage
        }
      }
    }
  }`;

graphql(schema, query)
  .then((result) => {
    console.log(result);
  });

Supported mongoose types

  • Number
  • String
  • Boolean
  • Date
  • [Number]
  • [String]
  • [Boolean]
  • [Date]
  • ObjectId with ref (reference to other document, populate)

Supported query types

  • query
    • singular: for example user
    • plural: for example users
    • node: takes a single argument, a unique !ID, and returns a Node
    • viewer: singular and plural queries as fields

Supported query arguments

  • indexed fields
  • "id" on singular type
  • array of "id"s on plural type

Which means, you are able to filter like below, if the age is indexed in your mongoose model:

users(age: 19) {}
user(id: "mongoId1") {}
user(id: "relayId") {}
users(id: ["mongoId", "mongoId2"]) {}
users(id: ["relayId1", "relayId2"]) {}

Supported mutation types

  • mutation
    • addX: for example addUser
    • updateX: for example updateUser
    • deleteX: for example deleteUser

Supported mutation arguments

  • scalar types
  • arrays
  • references

Examples:

mutation addX {
  addUser(input: {name: "X", age: 11, clientMutationId: "1"}) {
    changedUserEdge {
      node {
        id
        name
      }
    }
  }
}
mutation updateX {
  updateUser(input: {id: "id=", age: 10, clientMutationId: "2"}) {
    changedUser {
      id
      name
      age
    }
  }
}
mutation deleteX {
  deleteUser(input: {id: "id=", clientMutationId: "3"}) {
    ok
  }
}

Resolve hooks

You can specify pre- and post-resolve hooks on fields in order to manipulate arguments and data passed in to the database resolve function, and returned by the GraphQL resolve function.

You can add hooks to type fields and query fields (singular & plural queries, mutations) too. By passing arguments to the next function, you can modify the parameters of the next hook or the return value of the resolve function.

Examples:

  • Query, mutation hooks (viewer, singular, plural, mutation)
const hooks = {
  viewer: {
    pre: (next, root, args, request) => {
      // authorize the logged in user based on the request
      authorize(request);
      next();
    },
    post: (next, value) => {
      console.log(value);
      next();
    }
  },
  // singular: {
  //   pre: (next, root, args, context) => next(),
  //   post: (next, value, args, context) => next()
  // },
  // plural: {
  //   pre: (next, root, args, context) => next(),
  //   post: (next, value, args, context) => next()
  // },
  // mutation: {
  //   pre: (next, args, context) => next(),
  //   post: (next, value, args, context) => next()
  // }
};
const schema = getSchema([User], {hooks});
  • Field hooks
const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    hooks: {
      pre: (next, root, args, request) => {
        // authorize the logged in user based on the request
        // throws error if the user has no right to request the user names
        authorize(request);
        next();
      },
      // manipulate response
      post: [
        (next, name) => next(`${name} first hook`),
        (next, name) => next(`${name} & second hook`)
      ]
    }
  }
});
query UsersQuery {
  viewer {
    users(first: 1) {
      edges {
        node {
          name
        }
      }
    }
  }
}
{
  "data": {
    "viewer": {
      "users": {
        "edges": [
          {
            "node": {
              "name": "User0 first hook & second hook"
            }
          }
        ]
      }
    }
  }
}

Test

npm test

Contributing

Please read the CONTRIBUTING.md file.

License

MIT

More Repositories

1

react-easy-state

Simple React state management. Made with ❤️ and ES6 Proxies.
JavaScript
2,559
star
2

graffiti

⚠️ DEVELOPMENT DISCONTINUED - Node.js GraphQL ORM
JavaScript
1,009
star
3

node-style-guide

A mostly reasonable approach to JavaScript - how we write Node.js at RisingStack
992
star
4

graphql-server

Example GraphQL server with Mongoose (MongoDB) and Node.js
JavaScript
846
star
5

risingstack-bootcamp

This is the Node.js Bootcamp we ask new recruits at RisingStack to finish in their first weeks. It helps to get the basics right, and prepare you to work on enterprise projects.
JavaScript
703
star
6

multi-process-nodejs-example

JavaScript
516
star
7

trace-nodejs

Trace is a visualised distributed tracing platform designed for microservices.
JavaScript
471
star
8

protect

Proactively protect your Node.js web services
JavaScript
401
star
9

node-typescript-starter

TypeScript
351
star
10

react-way-getting-started

The React Way: Getting Started
JavaScript
343
star
11

example-prometheus-nodejs

Prometheus monitoring example with Node.js
JavaScript
332
star
12

nodehero-authentication

JavaScript
231
star
13

react-way-immutable-flux

React.js way with ES6, Immutable.js and Flux
JavaScript
224
star
14

kubernetes-graceful-shutdown-example

Example app for graceful start and stop with Kubernetes and Node.js
JavaScript
167
star
15

kubernetes-nodejs-example

Node.js example application with Kubernetes and CircleCI config
JavaScript
149
star
16

opentracing-auto

Out of the box distributed tracing for Node.js applications with OpenTracing.
JavaScript
133
star
17

http2-push-example

HTTP/2 Push example
JavaScript
129
star
18

event-sourcing-example

Event Sourcing Example repo for the Node.js at Scale blog series
JavaScript
87
star
19

node-with-rust

JavaScript
87
star
20

cqrs-example

CQRS: Command Query Responsibility Segregation - Node.js at Scale
JavaScript
83
star
21

koa-prerender

KOA middleware for prerendering javascript-rendered pages on the fly for SEO
JavaScript
77
star
22

react-baby-steps

Zero to Redux through Flux (with Rx) in baby steps
JavaScript
67
star
23

jaeger-node

Out of the box distributed tracing for Node.js applications.
JavaScript
67
star
24

mysql-large-data-handling

Code for the blogpost about handling large amount of data in Node
JavaScript
60
star
25

graffiti-todo

Example Relay TodoMVC application using graffiti-mongoose
JavaScript
58
star
26

example-http-timings

Example HTTP Timings in Node.js
JavaScript
50
star
27

example-kubernetes-nodejs

Introduction to Kubernetes with Node.js
JavaScript
50
star
28

training-microservices

Node.js Microservices training
49
star
29

docker-node

Dockerfiles for running Node.js
JavaScript
45
star
30

writing-testable-apis-the-basics

Writing testable HTTP APIs - the basics
JavaScript
43
star
31

anchor

Turns Kubernetes resources into a Helm chart
JavaScript
38
star
32

nodehero-testing

JavaScript
37
star
33

pact-example

This is an example of using pact-js with node.
JavaScript
34
star
34

Swiftify-iOS

Run Node.js code with Browserify on iOS
Swift
28
star
35

colorblinder

An example React-Native game for the series "Learning React-Native as a React developer: a definitive guide".
JavaScript
28
star
36

webinar-kubernetes-api-gateway

Microservices​ ​with​ ​Node.js​ ​and​ ​Kubernetes​
JavaScript
26
star
37

training-microservices-v3

Microservices training
JavaScript
19
star
38

opentracing-infrastructure-graph

Infrastructure visualisation via OpenTracing instrumentation
JavaScript
16
star
39

debug-node-docker

Code of the "How to debug a Node app in a Docker container" post on https://blog.risingstack.com
JavaScript
14
star
40

docker-codeship-project

JavaScript
13
star
41

opentracing-metrics-tracer

Exports cross-process metrics via OpenTracing to Prometheus.
JavaScript
13
star
42

nodejs-at-scale-handling-async

Article examples to handle async for the Node.js at Scale series.
JavaScript
12
star
43

thorken

Redis based JWT session for Node.js with the power of Thor
JavaScript
11
star
44

trace-go

Trace is a visualised stack trace platform designed for microservices.
Go
11
star
45

react-training

JavaScript
8
star
46

golang-tutorial-for-nodejs-developers-getting-started

This is the reference implematition for the "Golang Tutorial for Node.js Developers, Part I.: Getting started" blogpost at https://blog.risingstack.com/golang-tutorial-for-nodejs-developers-getting-started/
Go
8
star
47

post-stripe

Blog post about Stripe and Webshops: https://blog.risingstack.com/stripe-payments-integration-tutorial-javascript/
JavaScript
8
star
48

nrs

nsr - npm registry switcher
JavaScript
7
star
49

training-microservices-v2

Microservices training
JavaScript
7
star
50

post-stripe-api

API for Blog post about Stripe and Webshops: https://blog.risingstack.com/stripe-payments-integration-tutorial-javascript/
JavaScript
7
star
51

kubernetes-training

Shell
6
star
52

rising-url

Extends require('url').format() with parameters and easier inputs
JavaScript
6
star
53

auth0-ts-vue-example

Example repository for setting up Auth0 for Vue apps with TypeScript
TypeScript
6
star
54

cache

Stale / Expire Cache Implementation
JavaScript
6
star
55

rate-limiter

Rolling rate limiter
JavaScript
6
star
56

your-first-browserify-module

JavaScript
5
star
57

nuxt3-rendering-modes

Rendering modes showcase for nuxt 3
Vue
5
star
58

easy-state-hook-examples

Notes for a blogpost, nothing to see here (yet).
HTML
5
star
59

learnyougo

Go
5
star
60

surviving-web-security

Showcase for some of the Node.js / Web Security Best Practices
JavaScript
4
star
61

kubernetes-prometheus-nodejs

Monitoring with prometheus example
JavaScript
4
star
62

node-community-convention-training

JavaScript
3
star
63

endava_node

JavaScript
3
star
64

last-release-git-tag

GitHub Plugin for semantic-release
JavaScript
3
star
65

node-basics-skeleton

JavaScript
3
star
66

aha-news

TypeScript
3
star
67

oneshot-contest

JavaScript
3
star
68

shapeblinder

Fun demo project for the 2020 Dart and Flutter crash course series
Dart
3
star
69

profiler

JavaScript
3
star
70

expense_tracker

Expense tracker app
JavaScript
2
star
71

react-hooks-meetup

JavaScript
2
star
72

ncc-training

node community convention training
JavaScript
2
star
73

docker-node-base

JavaScript
1
star
74

find-port

Open port finder with Promise interface.
JavaScript
1
star
75

distributed-loadtests-jmeter

HCL
1
star
76

bc-node-example

JavaScript
1
star
77

node-hero-webinar-demo-app-authentication

1
star
78

almandite-user-service

Reference implementation of a user authentication service in GOlang!
Go
1
star
79

jsconfbp-2019-graphql

JavaScript
1
star
80

hwsw-adatbazis_muveletek

JavaScript
1
star
81

trace-cli

CLI for Trace by RisingStack: deployhook
JavaScript
1
star
82

silver-giggle

JavaScript
1
star
83

hwsw-react

JavaScript
1
star
84

demo-api

Demo Node API for testing your frontend's HTTP capabilities.
JavaScript
1
star
85

nuxt3-caching-with-auth

Demonstrate SWR and ISR rendering modes usage with auth
Vue
1
star