Git Product home page Git Product logo

graphpack's Introduction

Graphpack

☄️ A minimalistic zero-config GraphQL server

Check out the demo on CodeSandbox: https://codesandbox.io/s/k3qrkl8qlv


What is included?

Graphpack lets you create GraphQL servers with zero configuration. It uses webpack with nodemon and Apollo Server under the hood, so we get features like Live Reloading, GraphQL Playground, GraphQL Imports and many more right out of the box.

Install & Usage

yarn add --dev graphpack

Add src/schema.graphql and src/resolvers.js

src
├── resolvers.js
└── schema.graphql

In your schema, add some sample types in SDL:

type Query {
  hello: String
}

In src/resolvers.js:

const resolvers = {
  Query: {
    hello: () => 'world!',
  },
};

export default resolvers;

Setup package.json run scripts

Add following scripts to your package.json:

  "scripts": {
    "dev": "graphpack",
    "build": "graphpack build"
  },

Start development server

To start the development server, simply run:

yarn dev

Create production build

To create a production-ready build run following command:

yarn build

Use production build

Add following script that executes our build:

  "scripts": {
    "start": "node ./build/index.js"
  },

The following command will run the build and start the app

yarn start

Make sure to create a build before running the start script.

CLI Commands

graphpack (alias graphpack dev)

Runs graphpack in development mode. After a successful build your output should look something like this:

Graphpack

Graphpack will watch for changes in your ./src folder and automatically reload the server.

graphpack build

Creates a production-ready build under the project roots build folder.

Entry files

src/resolvers.js (required)

In this file you define all your resolvers:

// src/resolvers.js
const resolvers = {
  Query: {
    article: (obj, args) => getArticleById(args.id),
    articles: () => getArticles(),
  },
};

export default resolvers;

You can use any of these folder/file structure:

  • src/resolvers.js
  • src/resolvers/index.js

src/schema.graphql (required)

Here you define all your GraphQL type definitions:

# src/schema.graphql
type Article {
  title: String
  body: String
}

type Query {
  article: Article
  articles: [Article!]!
}

Alternatively you can create a src/schema.js and use the template literal tag gql by graphql-tag:

// src/schema.js
import { gql } from 'graphql-tag';

const typeDefs = gql`
  type Article {
    title: String
    body: String
  }

  type Query {
    article: Article
    articles: [Article!]!
  }
`;

export default typeDefs;

Note that in this case, you will need to install graphql-tag.

Graphpack can resolve both .js and .graphql files. This means you can use any of these folder/file structures:

  • src/schema.js
  • src/schema/index.js
  • src/schema.graphql
  • src/schema/index.graphql

src/context.js

Create src/context.js and do following:

const context = req => ({
  /* context props here */
});

export default context;

You can use any of these folder/file structures:

  • src/context.js
  • src/context/index.js

Custom configuration

For custom configuration you can create a graphpack config file in cosmiconfig format:

  • graphpack.config.js (recommended)
  • graphpack field in package.json
  • .graphpackrc in JSON or YAML
  • .graphpackrc with the extensions .json, .yaml, .yml, or .js

Note that the config file (eg. graphpack.config.js) is not going through babel transformation.

Customize Server configuration

In your graphpack.config.js configure your server as follows:

// graphpack.config.js
module.exports = {
  server: {
    introspection: false,
    playground: false,
    applyMiddleware: { app, path }, // app is from an existing (Express/Hapi,...) app
  },
};

Return config as a function to get the env variable:

// graphpack.config.js

// `mode` will be either `development` or `production`
module.exports = (mode) => {
  const IS_DEV = mode !== 'production';

  server: {
    introspection: IS_DEV,
    playground: IS_DEV,
    mocks: IS_DEV,
    mocks: IS_DEV,
    // ...
  }
};

export default config;

Refer to the Apollo Server docs for more details about the options.

Note that it's not possible to set resolvers, typeDefs or context in the config file. For this please refer to entry files.

Configure server port

Configure the server port with:

module.exports = {
  server: {
    port: 4000, // default,
  },
};

Applying express middlewares to the server

In your graphpack.config.js add your applyMiddleware field as follows:

// graphpack.config.js
const express = require('express');

const app = express();

app.get('/hello', (req, res) => {
  res.send('Hello world!');
});

module.exports = {
  server: {
    applyMiddleware: {
      app,
      path: '/graphql', // default
    },
  },
};

Your GraphQL endpoint will be available under http://localhost:4000/graphql. To configure the server options refer to https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#ApolloServer-applyMiddleware

Customize Webpack configuration

To extend webpack, you can define a function that extends its config via the config file:

// graphpack.config.js
module.exports = {
  webpack: ({ config, webpack }) => {
    // Add customizations to config
    // Important: return the modified config
    return config;
  },
};

Customize Babel configuration

Add an optional babel.config.js to your project root with the following preset:

// babel.config.js
module.exports = api => {
  // Cache the returned value forever and don't call this function again
  api.cache(true);

  return {
    presets: ['graphpack/babel'],
    // ... Add your plugins and custom config
  };
};

Acknowledgements

Graphpack was heavily inspired by:

Thanks to @richardbmx for designing the logo! 🙌

Contributors

This project exists thanks to all the people who contribute. contributors

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

MIT

graphpack's People

Contributors

dependabot[bot] avatar dougshamoo avatar farskid avatar glennreyes avatar iamnapo avatar imronras avatar mxstbr avatar pgilad avatar renovate-bot avatar rjoydip avatar usulpro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphpack's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (automergeMinor)

incompatibility with yarn workspaces

The problem

While using graphpack in a multi projects setup with yarn, the error below is thrown.

As a workaround, the whole project using graphpack can be moved to yarn's nohoist.

The workaround
package.json:

{
  "workspaces": {
    "packages": [
      "applications/**/*"
    ],
    "nohoist": [
      "appname-with-graphpack/**"
    ]
  }
}

The error

 error  in /my-app/node_modules/graphpack/lib/server.js

Module build failed (from /my-app/node_modules/graphpack/node_modules/babel-loader/lib/index.js):
Error: [BABEL] /my-app/node_modules/graphpack/lib/server.js: Cannot find module '@babel/preset-typescript' from '/my-app/applications/appname'
    at Function.module.exports [as sync] (/my-app/node_modules/resolve/lib/sync.js:43:15)
    at resolveStandardizedName (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:101:31)
    at resolvePreset (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:58:10)
    at loadPreset (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:77:20)
    at createDescriptor (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
    at items.map (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
    at Array.map (<anonymous>)
    at createDescriptors (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
    at createPresetDescriptors (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
    at presets (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)

 @ multi graphpack

/my-app/node_modules/graphpack/bin/graphpack.js:16
        throw Error(error || stats.toJson().errors);
        ^

Error: /my-app/node_modules/graphpack/lib/server.js
Module build failed (from /my-app/node_modules/graphpack/node_modules/babel-loader/lib/index.js):
Error: [BABEL] /my-app/node_modules/graphpack/lib/server.js: Cannot find module '@babel/preset-typescript' from '/my-app/applications/appname'
    at Function.module.exports [as sync] (/my-app/node_modules/resolve/lib/sync.js:43:15)
    at resolveStandardizedName (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:101:31)
    at resolvePreset (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:58:10)
    at loadPreset (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/files/plugins.js:77:20)
    at createDescriptor (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
    at items.map (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:109:50)
    at Array.map (<anonymous>)
    at createDescriptors (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
    at createPresetDescriptors (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
    at presets (/my-app/node_modules/graphpack/node_modules/@babel/core/lib/config/config-descriptors.js:47:19)
 @ multi graphpack index[0]
    at Watching.compiler.watch.once (/my-app/node_modules/graphpack/bin/graphpack.js:16:15)
    at Watching.<anonymous> (/my-app/node_modules/graphpack/node_modules/ramda/src/once.js:34:17)
    at Watching.handler (/my-app/node_modules/graphpack/node_modules/ramda/src/internal/_arity.js:14:19)
    at compiler.hooks.done.callAsync (/my-app/node_modules/graphpack/node_modules/webpack/lib/Watching.js:98:9)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/my-app/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
    at AsyncSeriesHook.lazyCompileHook (/my-app/node_modules/tapable/lib/Hook.js:154:20)
    at Watching._done (/my-app/node_modules/graphpack/node_modules/webpack/lib/Watching.js:97:28)
    at onCompiled (/my-app/node_modules/graphpack/node_modules/webpack/lib/Watching.js:47:18)
    at hooks.afterCompile.callAsync.err (/my-app/node_modules/graphpack/node_modules/webpack/lib/Compiler.js:552:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/my-app/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:15:1)
error Command failed with exit code 1.

Move src/config.js into graphpack.config.js

I'd like to move the server config in src/config.js into our graphpack.config.js, eg.:

// graphpack.config.js
module.exports = {
  webpack: ({ config }) => ({ ...config }),
  server: {
    playground: true,
    introspection: true,
  },
}

After #11 we should be able to pass middlewares like this:

// graphpack.config.js
const express = require('express');
const cors = require('cors');

const app = express();
// Additional middleware can be mounted at this point
app.use('*', jwtCheck, requireAuth, checkScope);

module.exports = {
  webpack: ({ config }) => ({ ...config }),
  server: {
    playground: true,
    introspection: true,
    applyMiddleware: { app },
  },
}

Note that graphpack.config.js is also used from outside of webpack. So ideally we can use both CommonJS or ES module imports in this file.

Problems while deploying to Google App Engine

Hi guys,

I am trying to deploy a simple graphpack project to GAE, but can't get GAE to resolve dependencies like "apollo-server" properly

I have this in my package.json:

  "scripts": {
    "dev": "graphpack",
    "build": "graphpack build",
    "start": "node ./build/index.js"
  },
  "dependencies": {
    "graphpack": "^1.0.0-alpha.3"
  }

GAE is running npm start to start-up the deployed app and it fails saying this:

Cannot find module 'apollo-server'

It is supposed to resolve dependencies using package.json (I am not uploading node_modules). But for some reason having "graphpack" in dependecies doesn't make it resolve "apollo-server" 😕

Do I have to run graphpack build on the server before running npm start to make it resolve dependencies correctly? And in this case is there a way to run graphpack build with npm?

https and wss support

Is there a way we can use https and wss today using the config?
I don't think so, but maybe you can correct me :-)

Support Dotenv

Similar to CRA, I've found it useful to have that supported out of the box.

support for structured GraphQL Schema

Hi, it's a feature request not a bug.

I think GraphQL schema could be more flexible than now.
For now, I have to define all GraphQL schema and resolver to schema.graphql, resolvers.js. I know resolvers are more options but not enough.

My proper structure for GraphQL is like this. each entry has own definitions.

src/
├── definitions
│   ├── groot
│   │   ├── groot.resolvers.js
│   │   └── groot.graphql
│   └── hello
│       ├── hello.resolvers.js
│       └── hello.graphql
└── index.js

3 directories, 5 files

However, this structure is not worked with graphqlpack. code sandbox has following error message.

Error: Couldn't find any resolvers. Please add resolvers to your src/resolvers.js
    at Module../node_modules/graphpack/lib/server.js

How about your thought on above GraphQL schema structure support?
I think merge-graphql-schemas can make things works easily. this repository will show you how to use the merge-graphql-schemas and what the benefits are. 😃

How to set subscription server

Could anyone help to provide subscription server? I could not understand how to configure. I want to keep both http and ws protocol running via graphpack

TypeScript support

graphpack looks awesome. Would be great if it would work out-of-the-box with TypeScript! 💪

GraphQL import throws

When importing other .graphql files from schema.graphql, building the server fails.

Minimal example in Codesandbox: https://codesandbox.io/s/q848mq9o1w

schema.graphql:

# import Post from "posts.graphql"

type Query {
  posts: [Post]
}

posts.graphql:

type Post {
  id: ID!
  text: String!
  tags: [String]
}

Output on the terminal:
image

I tried with v1.0.2 up to 1.0.8, also with "./posts.graphql", but without success. Any idea?

cosmiconfig(...).search() is not a function

I've run into an error, but I'm not sure what has triggered it. Here is the error message:

 DONE  Compiled successfully in 1121ms                                                        
...\build\index.js:103
const explorer = cosmiconfig('graphpack').search();
                                          ^

TypeError: cosmiconfig(...).search is not a function
    at Object../node_modules/graphpack/config/index.js (...\build\index.js:103:43)
    at __webpack_require__ (...\build\index.js:21:30)
    at Module../node_modules/graphpack/lib/server.js (...\build\index.js:240:65)
    at __webpack_require__ (...\build\index.js:21:30)
    at Object.0 (...\build\index.js:700:18)
    at __webpack_require__ (...\build\index.js:21:30)
    at ...\build\index.js:85:18
    at Object.<anonymous> (...\build\index.js:88:10)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)

I've tried running graphpack and graphpack build then node ./build/index.js, but both methods throw this error.

Inconsistent env object in config.js

Not sure if this is graphpack specific, but the following issue exists:

// src/config.js
const env = { ...process.env }
console.log(env) // returns object like { ..., NODE_ENV: "production", ... }
console.log(env.NODE_ENV) // returns "production"
console.log(process.env) // returns object like { ..., NODE_ENV: "production", ... }
console.log(process.env.NODE_ENV) // returns "production"

If I run the code with following commands it works as expected and line 2 & 4 and line 3 & 5 return the same values.

NODE_ENV="production" graphpack
# OR
NODE_ENV="production" graphpack build
NODE_ENV="production" node ./build/index.js

If I run the code with

graphpack build
NODE_ENV="production" node ./build/index.js

I get the following result, which is highly inconsistent and may confuse people:

// src/config.js
const env = { ...process.env }
console.log(env) // returns object like { ..., NODE_ENV: "production", ... }
console.log(env.NODE_ENV) // returns "production"
console.log(process.env) // returns object with key NODE_ENV undefined
console.log(process.env.NODE_ENV) // returns "development"

Error: Cannot find module 'core-js/proposals/array-flat-and-flat-map'

Hey
I just started to learn about GraphQL
Using graphpack was suggested by a guide on dev.to blog

I initialized a new project using yarn
Installed graphpack as suggested using yarn add -D graphpack
Created src dir, created index.js, resolvers.js and schema.graphql inside src just like the demo on CodeSandBox,
I added start to scripts in package.json
Tried to run it using yarn start/yarn run start

 DONE  Compiled successfully in 182ms                                 2:54:48 AM

internal/modules/cjs/loader.js:583
    throw err;
    ^

Error: Cannot find module 'core-js/proposals/array-flat-and-flat-map'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/home/alireza/Desktop/Tutorials/GraphQL/test/node_modules/apollo-env/lib/polyfills/array.js:3:1)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

I search alot in google, they were suggesting to install core-js global, even did that but didn't fix my problem

At last I took a look at your Demo, in package.json it was graphpack 1.0.2, So I tried the same stuff, but instead of yarn add -D graphpack I used yarn add -D [email protected] and the problem got fixed.

OS: Archlinux
Node Version: 10.15.1
Yarn Version: 1.13.0
NPM Version: 6.8.0

What can cause the problem with graphpack 1.0.6!?

Problems with reloading in development

Thanks for this amazing project, @glennreyes!

Reloading doesn't seem to happen properly on my machine. Compilation seems to happen correctly, but the old server code continues to run.

Setup:

  • Followed the first steps of the Readme until running a development server.
  • yarn.lock for package versions

Output in the terminal:

 DONE  Compiled successfully in 160ms                                                                                                                                        22:33:26

events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::4000
    at Server.setupListenHandle [as _listen2] (net.js:1286:14)
    at listenInCluster (net.js:1334:12)
    at Server.listen (net.js:1421:7)
    at resolve (/Users/thomasklemm/Code/experiments/testing-graphpack/node_modules/apollo-server/dist/index.js:74:28)
    at new Promise (<anonymous>)
    at ApolloServer.<anonymous> (/Users/thomasklemm/Code/experiments/testing-graphpack/node_modules/apollo-server/dist/index.js:72:19)
    at Generator.next (<anonymous>)
    at fulfilled (/Users/thomasklemm/Code/experiments/testing-graphpack/node_modules/apollo-server/dist/index.js:4:58)
Emitted 'error' event at:
    at Server.emit (events.js:182:13)
    at emitErrorNT (net.js:1313:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)

Unable to log?

Whenever I run graphpack on my project, I am unable to make use of console.log - is this meant to happen? Because I'm not sure. If it is, is there a workaround?

uni tests / CI

We should check how we could test graphpack using Travis CI.

Flow support

I see that graphpack supports TypeScript out of the box (#12), how about Flowtype? Would that only require adding a custom Babel configuration?

Monorepo

So we can publish a separate babel-preset-graphpack.

Analysis: 91% of dependency updates in this repository can be merged.

Hey there 👋

Our bot, Adaptly, found that 21 out of 23 currently open dependency update PRs can be merged.
That's 91% right there:

View Safe to Merge PRs1. Bump object-path from 0.11.4 to 0.11.8
2. Bump tar from 4.4.13 to 4.4.19
3. Bump path-parse from 1.0.6 to 1.0.7
4. Bump browserslist from 4.7.1 to 4.16.6
5. Bump hosted-git-info from 2.8.5 to 2.8.9
6. Bump lodash from 4.17.15 to 4.17.21
7. Bump handlebars from 4.4.5 to 4.7.7
8. Bump ssri from 6.0.1 to 6.0.2
9. Bump y18n from 4.0.0 to 4.0.1
10. Bump elliptic from 6.5.1 to 6.5.4
11. Bump ini from 1.3.5 to 1.3.7
12. Bump node-fetch from 2.6.0 to 2.6.1
13. Bump yargs-parser from 15.0.0 to 15.0.1
14. Bump apollo-server-express from 2.9.7 to 2.14.2
15. Bump apollo-server-core from 2.9.7 to 2.14.2
16. Bump apollo-server from 2.9.7 to 2.14.2
17. Bump acorn from 6.3.0 to 6.4.1
18. Update dependency ramda to ^0.27.0
19. Update dependency apollo-server to v2.11.0
20. Update dependency cosmiconfig to v6
21. Pin dependencies

feels

🔎   How does Adaptly know this?

It analyses changelogs of dependencies updated in a PR.
If no breaking changes are found in the changelogs, PR is marked as safe to merge.

✨ Try Adaptly yourself

Feel free to try Adaptly on your repositories and finally
merge the Dependabot PRs. Let us know if you have any questions.

Best of luck with your projects,
Lauris
[email protected]

Support applying server middlewares

We need to be able to import the server instance to apply middlewares on it.

For example, in src/config.js adding following:

import { server } from 'graphpack';

server.applyMiddleware(/* ... */);

More details about applying middlewares in the Apollo Server docs.

Logo

Not a high prio, but highly appreciated if someone feels like designing a logo for Graphpack.

How to connect with databases

Hi,

I want to use Database connection with GraphQL like MySQL, MongoDB and MSSQL.

What libraries do I need to install and configure, so I can use MySQL, MongoDB and MSSQL connection

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.