### Run benchmarks locally Source: https://github.com/aerogear/graphback/blob/master/performance/README.md Install dependencies and start the benchmarking process on your local machine. ```shell yarn yarn start ``` -------------------------------- ### Start the server with npm Source: https://github.com/aerogear/graphback/blob/master/templates/ts-apollo-mongodb-backend/README.md Start the development server using the npm package manager. ```bash npm run develop ``` -------------------------------- ### Install project dependencies Source: https://github.com/aerogear/graphback/blob/master/templates/ts-react-apollo-client/README.md Run this command to install the necessary dependencies for the project. ```bash yarn install ``` -------------------------------- ### Install @graphback/codegen-client Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/client-crud-plugin.md Install the plugin package as a dependency in your project. ```bash yarn add @graphback/codegen-client ``` -------------------------------- ### Start the React application Source: https://github.com/aerogear/graphback/blob/master/templates/ts-react-apollo-client/README.md Execute this command within the client directory to start the development server. ```bash yarn start ``` -------------------------------- ### Start the development server Source: https://github.com/aerogear/graphback/blob/master/templates/ts-apollo-mongo-apache-kafka-backend/README.md Commands to start the application server using npm or yarn. ```shell npm run develop ``` ```shell yarn develop ``` -------------------------------- ### Install Graphback package Source: https://github.com/aerogear/graphback/blob/master/docs/getting-started/adding-graphback-to-your-project.md Command to install the core Graphback package. ```bash npm install graphback ``` -------------------------------- ### Start the server with yarn Source: https://github.com/aerogear/graphback/blob/master/templates/ts-apollo-mongodb-backend/README.md Start the development server using the yarn package manager. ```bash yarn develop ``` -------------------------------- ### Start server with data synchronization Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Enable data synchronization features when starting the server. ```bash gqlserve serve Note.graphql --datasync ``` -------------------------------- ### Install graphback-cli Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/client-crud-plugin.md Install the Graphback CLI as a devDependency to execute plugins on-demand. ```bash yarn add -D graphback-cli ``` -------------------------------- ### Start infrastructure with Docker Compose Source: https://github.com/aerogear/graphback/blob/master/templates/ts-apollo-mongo-apache-kafka-backend/README.md Starts the database, Apache Kafka, and Zookeeper services required for the project. ```shell docker-compose up -d ``` -------------------------------- ### Install @graphback/codegen-schema Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/schema-crud-plugin.md Install the plugin package using yarn. ```bash yarn add @graphback/codegen-schema ``` -------------------------------- ### Install graphql-migrations with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/intro.md Install the required packages using yarn. ```bash yarn add graphql-migrations knex ``` -------------------------------- ### Install graphql-migrations with npm Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/intro.md Install the required packages using npm. ```bash npm i graphql-migrations knex ``` -------------------------------- ### Install @graphback/datasync Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/intro.md Install the data synchronization package via npm. ```bash npm install @graphback/datasync ``` -------------------------------- ### Install Graphback Knex Provider with npm Source: https://github.com/aerogear/graphback/blob/master/docs/databases/postgres.md Install the required packages using npm. ```bash npm install @graphback/runtime-knex knex ``` -------------------------------- ### Install Graphback Knex Provider with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/databases/postgres.md Install the required packages using yarn. ```bash yarn add @graphback/runtime-knex knex ``` -------------------------------- ### Start the GraphQL server Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Run the gqlserve serve command to start a server using the models in the current directory. ```bash gqlserve serve Note.graphql ``` -------------------------------- ### Start DataSync server with graphql-serve Source: https://github.com/aerogear/graphback/blob/master/website/blog/2020-10-1-graphback-datasync.md Use the graphql-serve CLI to start the server with the --datasync flag enabled on port 4000. ```shell npx graphql-serve serve model.graphql --datasync -p 4000 ``` -------------------------------- ### Install Keycloak dependencies Source: https://github.com/aerogear/graphback/blob/master/docs/authentication/keycloak.md Install the required keycloak-connect and keycloak-connect-graphql packages into your application. ```bash npm install keycloak-connect npm install keycloak-connect-graphql ``` -------------------------------- ### Install Knex and Graphback PostgreSQL library Source: https://github.com/aerogear/graphback/blob/master/docs/getting-started/adding-graphback-to-your-project.md Command to install the necessary dependencies for PostgreSQL database support. ```bash npm install knex @graphback/runtime-knex ``` -------------------------------- ### Install graphql-serve globally with npm Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Use this command to install the GraphQL Serve CLI tool globally using npm. ```bash npm i -g graphql-serve ``` -------------------------------- ### Start the GraphQL server Source: https://github.com/aerogear/graphback/blob/master/packages/graphql-serve/README.md Command to generate resolvers and start the server on a specified port using models from a directory. ```bash $ gqlserve serve models --port=8080 ``` -------------------------------- ### Install @graphql-tools/utils dependency Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md Install the required package to use the createResolvers hook. ```bash yarn add @graphql-tools/utils ``` -------------------------------- ### Install graphql-serve globally with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Use this command to install the GraphQL Serve CLI tool globally using yarn. ```bash yarn global add graphql-serve ``` -------------------------------- ### Install Graphback MongoDB Provider with npm Source: https://github.com/aerogear/graphback/blob/master/docs/databases/mongodb.md Use npm to install the required runtime and driver packages. ```bash npm install @graphback/runtime-mongo mongodb ``` -------------------------------- ### Install Graphback MongoDB Provider with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/databases/mongodb.md Use yarn to install the required runtime and driver packages. ```bash yarn add @graphback/runtime-mongo mongodb ``` -------------------------------- ### Create new documentation page Source: https://github.com/aerogear/graphback/blob/master/website/README.md Example of the front matter for a newly created documentation file. ```markdown --- id: newly-created-doc title: This Doc Needs To Be Edited --- My new content here.. ``` -------------------------------- ### Run graphql-serve with model files Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example command for running graphql-serve using a model file path. ```bash gqlserve serve ./path/to/models/*.graphql --port 8080 ``` -------------------------------- ### Install dependencies with npm Source: https://github.com/aerogear/graphback/blob/master/docs/cli/create-graphback.md Install project dependencies using the npm package manager. ```bash npm install ``` -------------------------------- ### Install dependencies with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/cli/create-graphback.md Install project dependencies using the yarn package manager. ```bash yarn ``` -------------------------------- ### Pagination Query Example Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example of using the page argument to limit and offset results. ```graphql findNotes(page: {limit: 10, offset:4}) { items { id } } ``` -------------------------------- ### Build the project Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Install dependencies and build the project using Yarn. ```shell yarn install yarn build ``` -------------------------------- ### Create new blog post Source: https://github.com/aerogear/graphback/blob/master/website/README.md Example of the front matter for a new blog post file. ```markdown --- author: Frank Li authorURL: https://twitter.com/foobarbaz authorFBID: 503283835 title: New Blog Post --- Lorem Ipsum... ``` -------------------------------- ### Ordering Query Example Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example of using the orderBy argument to sort results by a specific field. ```graphql findNotes(orderBy: {order: DESC, field: "likes"}) { items { id } } ``` -------------------------------- ### Start server on a specific port Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Use the --port flag to define the server port. ```bash $ gqlserve serve ./path/to/models --port 8080 Starting server... Listening at: http://localhost:8080/graphql ``` -------------------------------- ### Configure SchemaCRUDPlugin Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example of the simplified SchemaCRUDPlugin configuration using only outputPath. ```ts const schemaPlugin = new SchemaCRUDPlugin({ outputPath: './path/to/my/schema.js' }); ``` -------------------------------- ### Start development server Source: https://github.com/aerogear/graphback/blob/master/website/README.md Launch the development server in watch mode. If you encounter a file watcher limit error, increase the system limit using the provided command. ```bash # Start the site $ yarn start ``` ```bash echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p ``` -------------------------------- ### Delta Table Entry Example Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/conflict-resolution-intro.md An example of how a document is stored in the delta table for conflict resolution. ```json { "_id": { "$oid": "5f3b87ffcb1377481c391046" }, "docId": { "$oid": "5f3b87ffcb1377481c391045" }, "_version": 1, "document": { "text": "Bizarre", "description": "Who merged this stuff?", "_version": 1, "_deleted": false, "_lastUpdatedAt": 1597736959165, "_id": { "$oid": "5f3b87ffcb1377481c391045" } }, "_ttl": { "$date": "2020-08-25T07:49:19.181Z" } } ``` -------------------------------- ### Simple Find Query Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example of a basic query to retrieve all notes. ```graphql query { findNotes { items { id title likes } } } ``` -------------------------------- ### GraphQL query path example Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example query structure where the path parameter identifies the root field for selected fields. ```graphql query findNotes { findNotes { items { id title description } } } ``` -------------------------------- ### PostgreSQL list of relations output Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/intro.md Example output showing the relations created in a PostgreSQL database after running the migration. ```sql \d List of relations Schema | Name | Type | Owner --------+-------------+----------+------------ public | note | table | postgresql public | note_id_seq | sequence | postgresql ``` -------------------------------- ### Configure .graphqlrc.yml Source: https://github.com/aerogear/graphback/blob/master/docs/cli/graphback-cli.md Example configuration file defining the schema path and Graphback plugins for schema, client, and datasync generation. ```yaml ## Please review configuration and adjust it for your own project schema: ./src/schema/schema.graphql extensions: graphback: model: ./model/**/*.graphql ## You can add as many Graphback plugins as you wish ## Here we are only adding the Schema and Client plugin plugins: graphback-schema: format: graphql outputPath: ./src/schema/schema.graphql graphback-client: format: 'graphql' outputFile: ./src/graphql/graphback.graphql graphback-datasync: format: 'graphql' packageName: '@graphback/datasync' outputPath: ./src/schema/schema.graphql ``` -------------------------------- ### Integrate Graphback with Apollo Server Source: https://github.com/aerogear/graphback/blob/master/docs/getting-started/adding-graphback-to-your-project.md This example shows how to initialize a Knex database provider and use buildGraphbackAPI to generate the necessary components for an Apollo server. ```ts import express from 'express'; import http from "http"; import { ApolloServer } from 'apollo-server-express'; // highlight-start import { buildGraphbackAPI } from 'graphback' import { createKnexDbProvider } from '@graphback/runtime-knex' // highlight-end const app = express(); const schema = ` // highlight-start """ @model """ // highlight-end type Note { id: ID! text: String! archived: Boolean! } type Query { getAllNotes(): [Note]! } ` // highlight-start // create a Knex client const knex = Knex({ client: 'pg', connection: { host: '127.0.0.1', user: 'your_db_user', password: 'your_db_password', database: 'your_app_db' } }); // highlight-end // highlight-start // create a Knex database provider creator const knexDbProviderCreator = createKnexDbProvider(knex); // highlight-end // highlight-start // creates a schema, CRUD resolvers, services and data providers const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(schema, { dataProviderCreator: knexDbProviderCreator }); // highlight-end const server = new ApolloServer({ // highlight-start typeDefs, // your schema as a string resolvers: [resolvers, noteResolvers], // merge Graphback resolvers with your own // highlight-next-line context: contextCreator // creates a context with Graphback services attached // highlight-end }); server.applyMiddleware({ app }); const httpServer = http.createServer(app) apolloServer.installSubscriptionHandlers(httpServer) app.listen({ port: 4000 }, () => { console.log('Apollo Server on http://localhost:4000/graphql'); }); ``` -------------------------------- ### Initialize KeycloakCRUDService in Graphback Source: https://github.com/aerogear/graphback/blob/master/docs/authentication/keycloak.md This example demonstrates setting up runtime services in Graphback using createKeycloakCRUDService, defining auth rules, and configuring the ApolloServer context. ```ts import { ApolloServer } from 'apollo-server-express' import { createKeycloakCRUDService } from '@graphback/keycloak-authz' import { KnexDbDataProvider } from '@graphback/runtime-knex' import { PubSub } from 'graphql-subscriptions' import * as Knex from 'knex' import { buildGraphbackAPI, createCRUDService } from 'graphback' // the application model const model = ` """ @model """ type Task { id: ID! title: String! description: String! }` // the auth rules for the application const authConfig = { Task: { create: {}, read: {}, update: { roles: ["admin"] }, delete: { roles: ["admin"] } } } // set up the Knex database client const db = Knex({...}) // standard Graphback runtime setup const pubSub = new PubSub() const keycloakService = createKeycloakCRUDService(authConfig, createCRUDService({ pubSub: new PubSub() })); const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, { serviceCreator: keycloakService, dataProviderCreator: createKnexDbProvider(db) }); const server = new ApolloServer({ typeDefs, resolvers, context: (context) => { return { ...contextCreator(context), kauth: new KeycloakContext({ req: context.req }) } } }) ``` -------------------------------- ### Lerna version selection output Source: https://github.com/aerogear/graphback/blob/master/scripts/release-procedure.adoc Example output showing the interactive Lerna prompt for selecting a new version. ```bash lerna info version 2.9.0 lerna info current version 0.0.0 lerna info Checking for updated packages... lerna info Comparing with initial commit. lerna info Checking for prereleased packages... ? Select a new version (currently 0.0.0) Patch (0.0.1) ? Are you sure you want to publish the above changes? Yes Repository is ready for release. ``` -------------------------------- ### Install Graphback CLI with npm Source: https://github.com/aerogear/graphback/blob/master/docs/cli/graphback-cli.md Use this command to add the Graphback CLI as a development dependency to your project using npm. ```bash npm install --save-dev graphback-cli ``` -------------------------------- ### Run graphql-serve with npx Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Use this command to execute GraphQL Serve directly using npx without a global installation. ```bash npx graphql-serve ``` -------------------------------- ### Query naming format for get operation Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md The get operation follows the get naming convention to fetch a single item by its unique ID. ```graphql type Query { getNote(id: ID!): Note } ``` -------------------------------- ### Initialize a project with GraphQL CLI Source: https://github.com/aerogear/graphback/blob/master/website/blog/2020-10-01-announcing-graphback-1.0.md Use the GraphQL CLI to bootstrap a new project from a template. ```shell $ npx graphql-cli init ? Select the best option for you I want to create a new project from a GraphQL CLI Project Template. ? What is the name of the project? cool-graphback-project ``` -------------------------------- ### get Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md The get operation allows the client to fetch a single item from the database by its unique ID. ```APIDOC ## GraphQL Query: get ### Description The `get` operation allows the client to fetch a single item from the database by its unique ID. The resolver automatically maps the provided ID to the model's primary key field. ### Arguments - **id** (ID!) - Required - The unique ID of the object. ### Example ```graphql getNote(id: "tommyshelby@gmail.com") { id email name } ``` ``` -------------------------------- ### Subscribe to updatedNote with filters Source: https://github.com/aerogear/graphback/blob/master/docs/crud/subscriptions.md Example of applying filters to an updatedNote subscription. ```graphql subscription { updatedNote(filter: { likes: { gt: 100 }, title: { contains: 'football' } }) { id title likes } } ``` -------------------------------- ### Note model and generated CreateNoteInput Source: https://github.com/aerogear/graphback/blob/master/docs/crud/mutations.md Example of a Note model and the corresponding CreateNoteInput type generated by Graphback. ```graphql """ @model """ type Note { id: ID! title: String! description: String """ @manyToOne(field: 'notes', key: 'authorId') """ author: User } // highlight-start input CreateNoteInput { title: String! description: String authorId: ID } // highlight-end ``` -------------------------------- ### PostgreSQL index output Source: https://github.com/aerogear/graphback/blob/master/docs/model/annotations.md The resulting index definitions in PostgreSQL for the previous @index example. ```text "user_name_index" btree (name) "userEmail_index" hash (email) ``` -------------------------------- ### Install Graphback CLI with yarn Source: https://github.com/aerogear/graphback/blob/master/docs/cli/graphback-cli.md Use this command to add the Graphback CLI as a development dependency to your project using yarn. ```bash yarn add --dev graphback-cli ``` -------------------------------- ### Minimal Apollo GraphQL server setup Source: https://github.com/aerogear/graphback/blob/master/docs/getting-started/adding-graphback-to-your-project.md A basic Apollo server implementation using Express, defining a Note type and a resolver for fetching notes. ```typescript import express from 'express'; import { ApolloServer } from 'apollo-server-express'; const app = express(); const schema = ` type Note { id: ID! text: String! archived: Boolean! } type Query { getAllNotes(): [Note]! } ` const noteResolvers = { Query: { getAllNotes: (parent, args, context) => { return context.db.getAllNotes(); } } } const server = new ApolloServer({ typeDefs: schema, resolvers: noteResolvers }); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () => { console.log('Apollo Server on http://localhost:4000/graphql'); }); ``` -------------------------------- ### Note Model and MutateNoteInput Source: https://github.com/aerogear/graphback/blob/master/docs/crud/mutations.md An example of a Note model and the corresponding MutateNoteInput type generated by Graphback. ```graphql """ @model """ type Note { id: ID! title: String! description: String } // highlight-start input MutateNoteInput { id: ID! title: String description: String } // highlight-end ``` -------------------------------- ### Subscribe to newNote event Source: https://github.com/aerogear/graphback/blob/master/docs/crud/subscriptions.md Example of subscribing to the create mutation event for the Note type. ```graphql subscription { newNote { id title likes } } ``` -------------------------------- ### Initialize project with npx Source: https://github.com/aerogear/graphback/blob/master/docs/cli/create-graphback.md Use npx to initialize a new Graphback project named my-project. ```bash npx create-graphback my-project ``` -------------------------------- ### Edit existing blog post Source: https://github.com/aerogear/graphback/blob/master/website/README.md Example of the front matter and content structure for an existing blog post. ```markdown --- id: post-needs-edit title: This Blog Post Needs To Be Edited --- Edit me... ``` -------------------------------- ### Initialize project with npm init Source: https://github.com/aerogear/graphback/blob/master/docs/cli/create-graphback.md Use npm init to initialize a new Graphback project named my-project. ```bash npm init graphback my-project ``` -------------------------------- ### Edit existing documentation page Source: https://github.com/aerogear/graphback/blob/master/website/README.md Example of the front matter and content structure for an existing documentation page. ```markdown --- id: page-needs-edit title: This Doc Needs To Be Edited --- Edit me... ``` -------------------------------- ### PostgreSQL note table schema output Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/intro.md Example output showing the structure of the generated note table in PostgreSQL. ```sql \d note Table "public.note" Column | Type | Modifiers --------+------------------------+--------------------------------------------------- title | character varying(255) | not null id | integer | not null default nextval('note_id_seq'::regclass) Indexes: "note_pkey" PRIMARY KEY, btree (id) ``` -------------------------------- ### Define business model for plugin Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md The GraphQL schema model used as the basis for the plugin examples. ```graphql """ @model """ type Note { id: ID! title: String! archived: Boolean! description: String """ @oneToMany(field: 'note') """ comments: [Comment]! } """ @model """ type Comment { id: ID! text: String archived: Boolean! description: String } ``` -------------------------------- ### Implement createResources in MyGraphbackPlugin Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md Use createResources to output files like GraphQL schemas. This example writes the schema SDL to a file using writeFileSync. ```ts import { GraphbackPlugin, GraphbackCoreMetadata } from 'graphback'; // highlight-start import { writeFileSync } from 'fs'; import { printSchema } from 'graphql'; // highlight-end export class MyGraphbackPlugin extends GraphbackPlugin { ... // highlight-start createResources(metadata: GraphbackCoreMetadata): void { const schema = metadata.getSchema() const schemaSDL = printSchema(schema) writeFileSync('./schema.graphql', schemaSDL); } // highlight-end } ``` -------------------------------- ### Initialize Graphback project with custom template Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Use the graphback init command with the --templateUrl flag to bootstrap a project using a custom template repository. ```bash graphback init name --templateUrl=https://github.com/aerogear/modern-appdev-workshop ``` -------------------------------- ### Delta Query Response Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/conflict-resolution-intro.md An example JSON response for the syncComments delta query. ```json { "data": { "syncComments": { "items": [ { "_id": "5f350f33c6656579a104057e", "text": "Bizarre", "description": "Who merged this stuff?", "_lastUpdatedAt": 1597312819010, "_deleted": false, "_version": 1 } ], "lastSync": 1597312854109, "limit": null } } } ``` -------------------------------- ### Initialize DataSync API with createDataSyncAPI Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/intro.md Use the createDataSyncAPI function to wrap buildGraphbackAPI for a simplified setup. ```typescript import { createDataSyncAPI } from '@graphback/datasync' const { typeDefs, resolvers, contextCreator } = createDataSyncAPI(modelDefs, { db }); ``` -------------------------------- ### Example GraphQL Model for Comments Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/api-reference.md A sample GraphQL model demonstrating how type and field descriptions are used as table and column comments. ```graphql """ Note business model table comment. @model """ type Note { id: ID! """ Note title. """ title: String! } ``` -------------------------------- ### Subscribe to updatedNote event Source: https://github.com/aerogear/graphback/blob/master/docs/crud/subscriptions.md Example of subscribing to the update mutation event for the Note type. ```graphql subscription { updatedNote { id title likes } } ``` -------------------------------- ### Generated CRUD operations for a model Source: https://github.com/aerogear/graphback/blob/master/docs/crud/introduction.md This example shows the base model and the resulting queries, mutations, and subscriptions generated by Graphback. ```graphql """ @model """ type Note { id: ID! title: String! description: String likes: Int } // highlight-start type Query { getNote(id: ID!): Note findNotes(filter: NoteFilter, page: PageRequest, orderBy: OrderByInput): NoteResultList! } type Mutation { createNote(input: CreateNoteInput!): Note updateNote(input: MutateNoteInput!): Note deleteNote(input: MutateNoteInput!): Note } type Subscription { newNote(filter: NoteSubscriptionFilter): Note! updatedNote(filter: NoteSubscriptionFilter): Note! deletedNote(filter: NoteSubscriptionFilter): Note! } // highlight-end ``` -------------------------------- ### Subscribe to newNote with filters Source: https://github.com/aerogear/graphback/blob/master/docs/crud/subscriptions.md Example of applying filters to a newNote subscription to receive specific updates. ```graphql subscription { newNote(filter: { likes: { gt: 100 }, title: { contains: 'football' } }) { id title likes } } ``` -------------------------------- ### Configure plugin in .graphqlrc Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md Define plugin configuration in .graphqlrc. Use packageName to specify the package name when it starts with an @ symbol. ```yaml ... plugins: my-cool-plugin: format: 'graphql' packageName: '@your-namespace/my-cool-plugin' # Graphabck will load this package instead outputPath: './src/schema/schema.graphql' ``` -------------------------------- ### Create Graphback project Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/delta-queries.md Initialize a new project using the CLI, selecting the apollo-mongo-datasync-server-ts template. ```bash npx create-graphback datasync-project ``` -------------------------------- ### Migrate columns with a custom plugin Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/plugins.md Example showing how to merge two columns into one during migration by tapping into the column.drop operation and updating records via a Knex transaction. ```typescript import { migrateDB, MigratePlugin, WriteParams } from 'graphql-migrations'; const schema = ` """ @model """ type User { id: ID! """ db(oldNames: ['lname']) "" fullname: String } `; class MyPlugin implements MigratePlugin { write ({ tap }: WriteParams) { tap('column.drop', 'before', async (op: any, transaction: any) => { // Check the table and column if (op.table === 'user' && op.column === 'fname') { // Update the users lname with fname + ' ' + lname const users = await transaction .select('id', 'fname', 'lname') .from('user'); for (const user of users) { await transaction('user') .where({ id: user.id }) .update({ lname: `${user.fname} ${user.lname}` }) } } }) return true; } } const dbConfig = { // Knex database configuration } migrateDB(dbConfig, schema, { plugins: [ new MyPlugin(), ] }) ``` -------------------------------- ### View serve command help Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Display help information specifically for the serve command. ```bash $ gqlserve serve -h gqlserve serve [modelDir] [options] Generate and start GraphQL server from data model files Positionals: modelDir, model Directory to search for data models [string] Options: --port, -p Specify the port on which to listen on [number] --datasync, --ds Enable datasynchronization features [boolean] -h, --help Show help [boolean] -v, --version Show version number [boolean] Examples: gqlserve serve . -p 8080 generate schema from data model files in current directory and start GraphQL server on port 8080 ``` -------------------------------- ### Create a custom resolver with Graphback services Source: https://github.com/aerogear/graphback/blob/master/docs/resolvers/custom-resolvers.md This example demonstrates defining a custom query 'getDraftNotes' that utilizes the Graphback CRUD service to filter notes. ```typescript import { QueryFilter, GraphbackContext, buildGraphbackAPI } from "graphback"; import { GraphQLResolveInfo } from 'graphql'; import { NoteFilter } from '../generated-types'; // https://graphql-code-generator.com // define your model const model = ` """ @model """ type Note { id: ID! title: String! } // highlight-start type Query { getDraftNotes: [Note] } // highlight-end `; // create your own custom resolvers const customResolvers = { Query: { getDraftNotes: async (parent: any, args: any, context: GraphbackContext, info: GraphQLResolveInfo) => { const filter: QueryFilter = { title: { startsWith: '[DRAFT]' } } const results = await context.graphback.Note.findBy({ filter }, context, info); return results.items; } } } // generate Graphback schema and resolvers const { resolvers, typeDefs, contextCreator } = buildGraphbackAPI(model, { ... }); const apolloServer = new ApolloServer({ typeDefs, resolvers: [resolvers, noteResolvers], // merge Graphback and custom resolvers context: contextCreator }) ``` -------------------------------- ### Updating Note with Nested Metadata Source: https://github.com/aerogear/graphback/blob/master/docs/crud/mutations.md Example of updating a Note and its associated NoteMetadata in a single mutation. ```graphql mutation { updateNote(input: { id: 10, description: "Get prosecco for party", metadata: { createdAt: "2340349036", updatedAt: "2340349036" } }) { id title description metadata { createdAt updatedAt } } } ``` -------------------------------- ### Delta Query for syncComments Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/conflict-resolution-intro.md A GraphQL query example for retrieving items with a _version field to support delta synchronization. ```graphql query { syncComments(lastSync: 1590679886048) { items { _id text description _lastUpdatedAt _deleted _version }, lastSync, limit } } ``` -------------------------------- ### Usage of GraphQLResolveInfo with CRUD services Source: https://github.com/aerogear/graphback/blob/master/docs/resolvers/custom-resolvers.md Example of using info with a specific model service. Note that passing info is recommended only when fields are contained by the model. ```ts await context.Comment.findBy(args, context, info) ``` -------------------------------- ### GraphQL CRUD Query Schema Source: https://github.com/aerogear/graphback/blob/master/website/blog/2020-10-01-announcing-graphback-1.0.md Example of the auto-generated query schema provided by Graphback for CRUD operations. ```graphql type Query { findNotes(filter: NoteFilter, page: PageRequest, orderBy: OrderByInput): NoteResultList! getNote(id: ID!): Note findComments(filter: CommentFilter, page: PageRequest, orderBy: OrderByInput): CommentResultList! getComment(id: ID!): Comment } ``` -------------------------------- ### Implement a custom ConflictResolutionStrategy Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/conflict-resolution-strategies.md Create a custom strategy by implementing the resolveUpdate and resolveDelete methods as shown in the ClientSideWins example. ```typescript export const ClientSideWins: ConflictResolutionStrategy = { resolveUpdate(conflict: ConflictMetadata): any { // highlight-start const { serverData, clientDiff } = conflict const resolved = Object.assign(serverData, clientDiff); if (serverData[DataSyncFieldNames.deleted] === true) { resolved[DataSyncFieldNames.deleted] = false; } return resolved; // highlight-end }, resolveDelete(conflict: ConflictMetadata): any { // highlight-start const { serverData, clientData } = conflict; if (serverData[DataSyncFieldNames.deleted] === true) { throw new ConflictError(conflict); } const resolved = Object.assign(serverData, { [DataSyncFieldNames.deleted]: true }); return resolved // highlight-end } } ``` -------------------------------- ### Define a GraphQL model schema Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/plugins.md Example GraphQL schema definition using the @model directive for a User type. ```graphql """ @model """ type User { id: ID! fname: String lname: String } ``` -------------------------------- ### Typical Note Update Mutation Source: https://github.com/aerogear/graphback/blob/master/docs/crud/mutations.md Example of performing a partial update on a Note item using the updateNote mutation. ```graphql mutation { updateNote(input: { id: 10, description: "Get remainder of groceries" }) { id title description author { id name } } } ``` -------------------------------- ### Implement createResolvers in a Graphback plugin Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md Example of creating a custom query resolver within a Graphback plugin using the createResolvers hook. ```ts import { GraphbackPlugin, GraphbackCoreMetadata } from 'graphback'; import { GraphbackContext, getSelectedFieldsFromResolverInfo, QueryFilter } from '@graphback/core'; import { GraphQLResolveInfo } from 'graphql'; // highlight-start import { IResolvers, IObjectTypeResolver } from '@graphql-tools/utils'; // highlight-end export class MyGraphbackPlugin extends GraphbackPlugin { ... // highlight-start createResolvers(metadata: GraphbackCoreMetadata): IResolvers { const resolvers: IResolvers = {}; const queryObj: IObjectTypeResolver = {}; // loop through every Graphback model for (const model of metadata.getModelDefinitions()) { const modelName = model.graphqlType.name; // create a resolver function for every query field created in `transformSchema` queryObj[`getArchived${modelName}s`] = async (_: any, args: any, context: GraphbackContext, info: GraphQLResolveInfo) => { const crudService = context.graphback[modelName]; // create a filter in the GraphQLCRUD format to retrieve only archived Notes const customFilter: QueryFilter = { archived: { eq: true } }; // use the model service created by Graphback to query the database const { items } = await crudService.findBy({ filter: customFilter }); return items; } } resolvers.Query = queryObj; return resolvers; } // highlight-end } ``` -------------------------------- ### GraphQL Query for Nested Fields Source: https://github.com/aerogear/graphback/blob/master/docs/resolvers/custom-resolvers.md An example of an incoming GraphQL query requesting nested comments for draft notes. ```graphql query { getDraftNotes { comments { id, description } } } ``` -------------------------------- ### Note Model Definition Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example model using built-in scalar types for which Graphback generates filter inputs. ```graphql """ @model """ type Note { id: ID! title: String! opened: Boolean likes: Int completedPercentage: Float } ``` -------------------------------- ### Build the project Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Execute the build command for the project. ```shell yarn build ``` -------------------------------- ### Note model with metadata and generated input types Source: https://github.com/aerogear/graphback/blob/master/docs/crud/mutations.md Example showing how Graphback generates input types for models containing nested non-model GraphQL types. ```graphql """ @model """ type Note { id: ID! title: String! description: String metadata: NoteMetadata } """Regular non-model GraphQL type""" type NoteMetadata { createdAt: String updatedAt: String } // highlight-start input CreateNoteInput { title: String! description: String metadata: CreateNoteMetadataInput } input CreateNoteMetadataInput { createdAt: String updatedAt: String } // highlight-end ``` -------------------------------- ### View CLI help information Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Display the general help menu for the gqlserve CLI. ```bash $ gqlserve -h gqlserve Commands: gqlserve print-schema [modelDir] Generate and print GraphQL schema from data model files gqlserve serve [modelDir] [options] Generate and start GraphQL server from data model files Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] ``` -------------------------------- ### GraphQL Interface implementation Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example of using interfaces in a GraphQL schema to ensure data consistency. Note that interfaces are not currently considered during resolver or database generation. ```graphql interface Searchable { searchPreviewText: String! } interface Item { price: Int! } type Movie implements Searchable & Item { directory: String! searchPreviewText: String! price: Int! } ``` -------------------------------- ### Change directory to project folder Source: https://github.com/aerogear/graphback/blob/master/docs/cli/create-graphback.md Navigate into the newly created project directory. ```bash cd my-awesome-project ``` -------------------------------- ### Bootstrap a GraphQL server with Graphback Source: https://github.com/aerogear/graphback/blob/master/website/blog/2020-10-01-announcing-graphback-1.0.md Use the buildGraphbackAPI function to initialize your server with CRUD services and a Knex data provider. ```ts import { buildGraphbackAPI, createCRUDService } from 'graphback'; import { createKnexDbProvider } from '@graphback/runtime-knex'; import { PubSub } from 'graphql-subscriptions'; import Knex from 'knex'; const db = Knex(...); const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, { serviceCreator: createCRUDService({ pubSub: new PubSub() }) dataProviderCreator: createKnexDbProvider(db) }); const apolloServer = new ApolloServer({ typeDefs, resolvers, context: contextCreator }); ``` -------------------------------- ### GraphbackCRUDService findBy usage with FindByArgs Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example of calling findBy with the new FindByArgs interface. ```ts await noteService.findBy({ filter: { id: { gt: 100 } }, page: { offset: 0, limit: 10 }, orderBy: { field: 'id' } }) ``` -------------------------------- ### Subscribe to deletedNote event Source: https://github.com/aerogear/graphback/blob/master/docs/crud/subscriptions.md Example of subscribing to the delete mutation event for the Note type. ```graphql subscription { deletedNote { id title likes } } ``` -------------------------------- ### Run release preparation script Source: https://github.com/aerogear/graphback/blob/master/scripts/release-procedure.adoc Executes the preparation script from the root directory to update package versions. ```bash npm run release:prep ``` -------------------------------- ### Uninstall global CLI Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Remove any existing global installation of graphback-cli before linking the local version. ```shell npm uninstall -g graphback-cli ``` -------------------------------- ### Compare server performance Source: https://github.com/aerogear/graphback/blob/master/performance/README.md Run the comparison command to determine which server is faster. ```shell yarn compare ``` -------------------------------- ### Generate API documentation Source: https://github.com/aerogear/graphback/blob/master/website/README.md Run this command from the Graphback project root to generate API documentation from code comments into the docs/api/ folder. ```bash yarn generate:doc ``` -------------------------------- ### Initialize Knex client and provider Source: https://github.com/aerogear/graphback/blob/master/docs/getting-started/adding-graphback-to-your-project.md Configures the Knex client with database credentials and creates a provider for Graphback. ```typescript import Knex from 'knex'; import { createKnexDbProvider } from '@graphback/runtime-knex'; const knex = Knex({ client: 'pg', connection: { host: '127.0.0.1', user: 'your_db_user', password: 'your_db_password', database: 'your_app_db' } }) const knexProviderCreator = createKnexDbProvider(knex); ``` -------------------------------- ### View print-schema command help Source: https://github.com/aerogear/graphback/blob/master/docs/graphqlserve/graphqlserve.md Display help information specifically for the print-schema command. ```bash $ gqlserve print-schema -h gqlserve print-schema [modelDir] Generate and print GraphQL schema from data model files Positionals: modelDir, model Directory to search for data models [string] Options: -h, --help Show help [boolean] -v, --version Show version number [boolean] Examples: gqlserve print-schema modelDir only display generated schema from data model files in modelDir directory and quit ``` -------------------------------- ### GraphQL syncComments query Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/delta-queries.md Example query to retrieve changed comments since a specific timestamp. ```graphql query { syncComments(lastSync: 1590679886048) { items { _id text description _lastUpdatedAt _deleted }, lastSync, limit } } ``` -------------------------------- ### Implement SQLiteKnexDBDataProvider Source: https://github.com/aerogear/graphback/blob/master/docs/databases/sqlite.md Configure the database, perform migrations, and initialize the SQLiteKnexDBDataProvider for use with buildGraphbackAPI. ```ts import Knex from 'knex'; import { migrateDB } from 'graphql-migrations'; import { ModelDefinition } from '@graphback/core'; import { SQLiteKnexDBDataProvider } from '@graphback/runtime-knex'; // highlight-start // database configuration const dbConfig = { client: "sqlite3", connection: { filename: "./users.sqlite" } }; // create the connection to the database const db = Knex(dbConfig); // the business model const userModel = ` """ @model """ type User { id: ID! username: String! } `; // create the user table in database migrateDB(dbConfig, userModel, { }).then(() => { console.log("Migrated database"); }); // create the SQLite data provider const dataProviderCreator = (model: ModelDefinition) => new SQLiteKnexDBDataProvider(model, db); // highlight-end // Use the dataProvider in buildGraphbackAPI const { resolvers, services, contextCreator } = buildGraphbackAPI(userModel, { dataProviderCreator }); ``` -------------------------------- ### Query archived Notes and Comments Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/creating-your-own-plugin.md Example GraphQL query to retrieve archived notes and their associated comments. ```graphql query archivedNotesAndComments { getArchivedNotes { id title comments { id archived text } } getArchivedComments { id text note { id archived title } } } ``` -------------------------------- ### Initialize PostgreSQL Connection with Knex Source: https://github.com/aerogear/graphback/blob/master/docs/databases/postgres.md Initiate a connection to a local PostgreSQL database and configure a connection pool. ```ts import Knex from 'knex'; const dbConfig = { client: "pg", connection: { user: "postgresql", password: "password", database: "users", host: "localhost", port: 5432 }, pool: { min: 5, max: 30 } }; const db = Knex(dbConfig); ``` -------------------------------- ### Configure .graphqlrc Source: https://github.com/aerogear/graphback/blob/master/docs/plugins/client-crud-plugin.md Define the ClientCRUDPlugin (as graphback-client) within the .graphqlrc configuration file. Ensure graphback-schema is defined before it to use the latest schema. ```yaml schema: './src/schema.graphql' documents: './client/src/graphql/**/*.graphql' extensions: graphback: # path to data mode file(s) model: './model/datamodel.graphql' plugins: graphback-schema: outputPath: './src/schema/schema.graphql' graphback-client: outputFile: './client/src/graphql/graphback.graphql' ``` -------------------------------- ### Create Data Provider and Build Graphback API Source: https://github.com/aerogear/graphback/blob/master/docs/databases/postgres.md Configure the database, perform migrations, and create a data provider for use with buildGraphbackAPI. ```ts import Knex from 'knex'; import { migrateDB } from 'graphql-migrations'; import { createKnexDbProvider } from '@graphback/runtime-knex'; // highlight-start // database configuration const dbConfig = { client: "pg", connection: { user: "postgresql", password: "password", database: "users", host: "localhost", port: 5432 }, pool: { min: 5, max: 30 } }; // create the connection to the database const db = Knex(dbConfig); // the business model const userModel = ` """ @model """ type User { id: ID! username: String! } `; // create the user table in database migrateDB(dbConfig, userModel, { }).then(() => { console.log("Migrated database"); }); // create the postgres data provider const dataProviderCreator = createKnexDbProvider(db); // highlight-end // Use the dataProvider in buildGraphbackAPI const { resolvers, services, contextCreator } = buildGraphbackAPI(userModel, { dataProviderCreator }); ``` -------------------------------- ### Configure SQLite database with Knex Source: https://github.com/aerogear/graphback/blob/master/docs/databases/sqlite.md Define the database configuration object and initialize the Knex instance for SQLite. ```ts import Knex from 'knex'; const dbConfig = { client: "sqlite3", connection: { filename: "./users.sqlite" } }; const db = Knex(dbConfig); ``` -------------------------------- ### Model definition with primary key Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example of a model definition where the @id directive identifies the primary key field. ```graphql """ @model """ type User { """@id""" email: String name: String } ``` -------------------------------- ### Model definition with oneToMany relationship Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/delta-queries.md Example model definition where Note has a oneToMany relationship to Comment, which is marked for datasync. ```graphql """ @model """ type Note { _id: GraphbackObjectID! title: String! """ @oneToMany(field: 'note') """ comments: [Comment]! } """ @model @datasync """ type Comment { _id: GraphbackObjectID! text: String } ``` -------------------------------- ### Graphback individual packages list Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md List of individual packages available for configuring generators and other capabilities within the Graphback ecosystem. ```text @graphback/codegen-client @graphback/codegen-resolvers @graphback/codegen-schema @graphback/core @graphback/runtime graphql-migrations ``` -------------------------------- ### Run benchmarks in Docker Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Launch the performance benchmark suite inside a Docker container. Ensure the project is built before running this command. ```shell yarn bench:docker ``` -------------------------------- ### Link CLI locally Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Link the local graphback-cli package to make it available globally for development. ```shell cd packages/graphback-cli npm link ``` -------------------------------- ### Define model with documentation Source: https://github.com/aerogear/graphback/blob/master/packages/graphql-migrations/README.md Use GraphQL documentation strings to provide metadata for tables and columns. ```gql """ Notes table """ type Note { """ Primary key """ id: ID! """ The note title """ title: String! } ``` -------------------------------- ### Switching Database Providers in buildGraphbackAPI Source: https://github.com/aerogear/graphback/blob/master/website/blog/2020-10-01-announcing-graphback-1.0.md Demonstrates how to swap between Knex and MongoDB providers by updating the dataProviderCreator configuration. ```ts ... // import { createKnexDbProvider } from '@graphback/runtime-knex'; // highlight-next-line import { createMongoDbProvider } from '@graphback/runtime-mongo'; import { DataSyncPlugin } from '@graphback/datasync'; const db = connectMongoDB(); const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, { // dataProviderCreator: createKnexDbProvider(db) // highlight-next-line dataProviderCreator: createMongoDbProvider(db) }); ``` -------------------------------- ### Query to retrieve a single user Source: https://github.com/aerogear/graphback/blob/master/docs/crud/queries.md Example of a query to retrieve a single user by their primary field, in this case, the email address. ```graphql getNote(id: "tommyshelby@gmail.com") { id email name } ``` -------------------------------- ### Run benchmarks in Docker Source: https://github.com/aerogear/graphback/blob/master/performance/README.md Execute benchmarks within a Docker container constrained to 256MB memory and 2 CPU cores. ```shell cd ../ yarn yarn bench:docker ``` -------------------------------- ### GraphQL syncComments response Source: https://github.com/aerogear/graphback/blob/master/docs/datasync/delta-queries.md Example JSON response containing updated items, a deletion flag, and the next sync timestamp. ```json { "data": { "syncComments": { "items": [ { "id": "5ee0a1da7f1f39313744185a", "text": "First!", "description": null, "_lastUpdatedAt": 1591852693075, "_deleted": true }, { "id": "5ee0a67345beff3862220be4", "text": "Second!", "description": null, "_lastUpdatedAt": 1591780979988, "_deleted": false } ], "lastSync": "1591852700920", "limit": null } } } ``` -------------------------------- ### Run tests with coverage Source: https://github.com/aerogear/graphback/blob/master/CONTRIBUTING.md Execute the test suite to verify functionality and check coverage. ```shell yarn test ``` -------------------------------- ### Connect to MongoDB Source: https://github.com/aerogear/graphback/blob/master/docs/databases/mongodb.md Establish a connection to a local MongoDB instance and retrieve a database instance. ```typescript import { Db, MongoClient } from "mongodb"; // Example Mongo Connection URL const url = 'mongodb://localhost:27017'; const mongoClient: MongoClient = await MongoClient.connect(url); // get db instance const db: Db = mongoClient.db('users'); ``` -------------------------------- ### Custom Scalar Mapping Implementation Source: https://github.com/aerogear/graphback/blob/master/docs/graphql-migrations/api-reference.md An example of using the scalarMap option to map a custom 'CustomDate' scalar to a database 'date' type. ```typescript import { migrateDB } from 'graphql-migrations'; const schemaText = ``` """ @model """ type Note { id: ID! title: String! createdAt: CustomDate } scalar CustomDate ```; const dbConfig = { // Knex.js db configuration }; migrateDB(dbConfig, schemaText, { scalarMap: ( field: GraphQLField, scalarType: GraphQLScalarType, annotations: any, ): TableColumnTypeDescriptor | null => { // custom date converted to date type if (scalarType.name === 'CustomDate') { return { type: 'date', args: [] } } return undefined } }).then((ops) => { console.log(ops); }); ``` -------------------------------- ### Graphback CLI configuration file structure Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Required structure for the graphback.json configuration file, replacing the previous config.json. ```json "folders": { "model": "./model", "resolvers": "./src/resolvers/", "schema": "./src/schema", "client": "./client/src/graphql" } ``` -------------------------------- ### Define 1:M relationship in GraphQL Source: https://github.com/aerogear/graphback/blob/master/docs/CHANGELOG-0.x.md Example of defining a one-to-many relationship in a GraphQL model, which triggers the creation of a foreign key column in the database. ```gql type User { id: ID! messages: [Message] } ```