Giter Club home page Giter Club logo

vue-cli-plugin-apollo's Introduction

vue-cli-plugin-apollo

npm npm vue-cli3 apollo-2

๐Ÿš€ Start building a Vue app with Apollo and GraphQL in 2 minutes!

This is a vue-cli 3.x plugin to add Apollo and GraphQL in your Vue project.

Become a Patreon


โญ Features:

  • Automatically integrate vue-apollo into your Vue app
  • Embed Apollo client config (upgradable)
  • Included optional Graphql API Server (upgradable):
    • Dead simple GraphQL API sources generated into your project
    • Upgradable service running apollo-server
    • Websocket subscriptions support
    • Optional automatic mocking
    • Optional Apollo Engine support
  • Included optional example component with:
    • Watched query
    • Mutation
    • Realtime subscription using Websockets
  • GraphQL validation using ESLint

Table of contents


Getting started

โš ๏ธ Make sure you have vue-cli 3.x.x:

vue --version

If you don't have a project created with vue-cli 3.x yet:

vue create my-new-app

Navigate to the newly created project folder and add the cli plugin:

cd my-new-app
vue add apollo

โ„น๏ธ An example ApolloExample.vue component alongside some GraphQL query files will be added into your sources if you chose to include the examples.

Start your app:

npm run serve

Updating vue-cli-plugin-apollo will also update both Apollo Client and its configuration for you! ๐Ÿ‘

Read the vue-apollo doc.

GraphQL API Server

If you enabled the GraphQL API Server, open a new terminal and start it:

npm run graphql-api

You can edit the files generated in the ./src/graphql-api folder:

  • schema.graphql contains the Schema written with the schema definition language.
  • resolvers.js declares the Apollo resolvers.
  • context.js allows injecting a context object into all the resolvers (third argument).
  • mocks.js defines the custom resolvers used for mocking (more info).
  • directives.js defines the custom schema directives (more info)).

The server will be automatically restarted when a change is detected.

To run the server only once, use this command:

npm run run-graphql-api

Updating vue-cli-plugin-apollo will also update the GraphQL Server service ๐Ÿ‘

Injected Commands

  • vue-cli-service graphql-api

    Run the GraphQL API server with info from ./src/graphql-api and watch the files to restart itself automatically.

  • vue-cli-service run-graphql-api

    Run the GraphQL API server with info from ./src/graphql-api once.

Configuration

Client state

You can use apollo-link-state for client-only local data with the clientState option of createApolloClient:

import { createApolloClient } from 'vue-cli-plugin-apollo/graphql-client'

const options = {
  // ...

  clientState: {
    defaults: {
      connected: false,
    },
    resolvers: {
      Mutation: {
        connectedSet: (root, { value }, { cache }) => {
          const data = {
            connected: value,
          }
          cache.writeData({ data })
        },
      },
    },
  },
}

const { apolloClient } = createApolloClient(options)

Then you need to use the @client directive:

query isConnected {
  connected @client
}
mutation setConnected ($value: Boolean!) {
  connectedSet (value: $value) @client
}

Authorization Header

By default, createApolloClient will retrieve the Authorization header value from localStorage. You can override this behavior with the getAuth option:

const options = {
  // ...

  getAuth: (tokenName) => getUserToken(),
}

const { apolloClient } = createApolloClient(options)

If you use cookies, you can return undefined.

Plugin options

The GraphQL API Server can be configured via the pluginOptions in vue.config.js:

module.exports = {
  // Other options...
  pluginOptions: {
    // Enable automatic mocking
    graphqlMock: true,
    // Enable Apollo Engine
    apolloEngine: true,

    /* Other options (with default values) */

    // Requests timeout (ms)
    graphqlTimeout: 120000,
  },
}

Apollo Server

You can set custom Apollo server options in a src/graphql-api/apollo.js file:

module.exports = req => {
  return {
    // Custom apollo server options here
    cacheControl: {
      defaultMaxAge: 1000,
    },
  }
}

Mocks

You can enable automatic mocking on the GraphQL API Server. It can be customized in the ./src/graphql-api/mocks.js file generated in your project.

Directives

You can add custom GraphQL directives in the ./src/graphql-api/directives.sjs file (documentation).

const { SchemaDirectiveVisitor } = require('graphql-tools')

class PrivateDirective extends SchemaDirectiveVisitor {
  // ...
}

module.exports = {
  // Now you can use '@private' in the schema
  private: PrivateDirective
}

Apollo Engine

Apollo Engine is a commercial product from Apollo. It enables lots of additional features like monitoring, error reporting, caching and query persisting.

Create a key at https://engine.apollographql.com (it's free!).

You can set custom Apollo Engine options in a src/graphql-api/engine.js file:

module.exports = {
  // Custom apollo engine options here
  stores: [
    { /* ... */ },
  ],
}

Express middlewares

If you need to add express middlewares into the GraphQL server, you can create a ./src/graphql-api/server.js file:

const path = require('path')
const express = require('express')
const distPath = path.resolve(__dirname, '../../dist')

module.exports = app => {
  app.use(express.static(distPath))
}

Env variables

  • VUE_APP_GRAPHQL_HTTP

    The url to the graphql HTTP endpoint, default: http://localhost:4000

  • VUE_APP_GRAPHQL_WS

    The url to the graphql Websockets endpoint for subscriptions, default: ws://localhost:4000

With the GraphQL server enabled

  • VUE_APP_GRAPHQL_PORT

    Port of the GraphQL API Server, default: 4000

  • VUE_APP_APOLLO_ENGINE_KEY

    API key for Apollo Engine

  • VUE_APP_GRAPHQL_PLAYGROUND_PATH

    Url path to the graphql server playground, default: '/'

  • VUE_APP_GRAPHQL_CORS

    Cors rules, default: '*'

Injected webpack-chain Rules

  • config.rule('gql')

Running the GraphQL server in production

cross-env NODE_ENV=production yarn run run-graphql-api --mode production

If your project is meant to be used as a package installed from npm, you will need to move vue-cli-plugin-apollo from the devDependencies field to dependencies in your package.json file.

Manual code changes

In case the plugin isn't able to modify the file containing the root Vue instance:

Import the provider:

import { createProvider } from './vue-apollo'

Then in the root instance, set the provide option:

new Vue({
  el: '#app',
  // Add this line
  provide: createProvider().provide(),
})

vue-cli-plugin-apollo's People

Contributors

akryum avatar ameistad avatar baskiers avatar drsensor avatar frandiox avatar vahdet avatar zephraph avatar

Watchers

 avatar  avatar  avatar

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.