Note: This package is under active development.
GraphQL schema directives to generate CRUD queries, mutations and resolvers which are automatically connected to a database.
Supported databases:
- Mongo
Database of your choice missing? Adding one is easy - implement the Store interface.
Available directives:
@model- Generates queries, mutations and resolvers for the annotated type.
- Install core package:
npm install graphql-crudoryarn add graphql-crud. - Install a store package:
- Mongo:
npm install graphql-crud-mongooryarn add graphql-crud-mongo.
- Mongo:
- Define your schema and annotate it with directives.
- Use
makeExecutableSchemato generate the schema. - Instantiate and assign your store to
directives.model.storeon the GraphQLcontext.
import { makeExecutableSchema } from 'graphql-tools';
import { execute } from 'graphql';
import gql from 'graphql-tag';
import crud from 'graphql-crud';
import MongoStore from 'graphql-crud-mongo';
import typeDefs from './typeDefs';
const typeDefs = `
type Author @model {
name: String!
books: [Book]
favoriteBook: Book
}
type Book @model {
name: String!
authors: [Author]
}
type Query {
_: Boolean
}
type Mutation {
_: Boolean
}
`
const schema = makeExecutableSchema({
typeDefs,
schemaDirectives: {
...crud
},
});
const context = {
directives: {
model: {
store: new MongoStore({ connection: 'mongodb://localhost/my-database' }),
},
},
};
execute(
schema,
gql`
mutation {
createAuthor(data: {
name:"Leo Tolstoy"
}) {
id
name
}
}
`
null,
context
);The above example will generate the following schema with functioning resolvers.
"type Author {
name: String
books: [Book]
id: ID
}
input AuthorInputType {
name: String
books: [BookInputType]
id: ID
}
type Book {
name: String
authors: [Author]
id: ID
}
input BookInputType {
name: String
authors: [AuthorInputType]
id: ID
}
type Mutation {
_: Boolean
createAuthor(data: AuthorInputType): Author
updateAuthor(data: UpdateAuthorInputType, where: UpdateAuthorInputType, upsert: Boolean): Boolean
removeAuthor(where: AuthorInputType): Boolean
createBook(data: BookInputType): Book
updateBook(data: UpdateBookInputType, where: UpdateBookInputType, upsert: Boolean): Boolean
removeBook(where: BookInputType): Boolean
}
type Query {
_: Boolean
author(where: AuthorInputType): Author
authors(where: AuthorInputType): [Author]
book(where: BookInputType): Book
books(where: BookInputType): [Book]
}
input UpdateAuthorInputType {
name: String
books: [UpdateBookInputType]
id: ID
}
input UpdateBookInputType {
name: String
authors: [UpdateAuthorInputType]
id: ID
}In the repo's root run the following:
docker-compose up -dto start dependent databases.npm installoryarn install
In examples/simple run the following:
npm install; npm startoryarn install; yarn start- Navigate to http://localhost:3000/graphiql
docker-compose up -dto start database dependencies for testing and the example.npm installoryarn install.npm run link:packagesoryarn link:packages.npm run build:watchoryarn build:watch- Write code.