Code Monkey home page Code Monkey logo

apollo-module's Introduction

Apollo inside of NuxtJS

  • Nuxt.js module to use vue-apollo (integrates graphql-tag loader to parse .gql & .graphql files)
  • uses internally same approach as vue-cli-plugin-apollo

npm version license

Setup

Install apollo module:

npm install --save @nuxtjs/apollo

Add @nuxtjs/apollo to modules section of nuxt.config.js

  • clientConfigs: Object Config passed to ApolloClient
    • default: Object
    • otherClient: Object (Optional)
{
  // Add apollo module
  modules: ['@nuxtjs/apollo'],

  // Give apollo module options
  apollo: {
    tokenName: 'yourApolloTokenName', // optional, default: apollo-token
    includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
    authenticationType: 'Basic', // optional, default: 'Bearer'
    // required
    clientConfigs: {
      default: {
        // required  
        httpEndpoint: 'http://localhost:4000',
        // You can use `wss` for secure connection (recommended in production)
        // Use `null` to disable subscriptions
        wsEndpoint: 'http://localhost:4000', // optional
        // LocalStorage token
        tokenName: 'apollo-token', // optional
        // Enable Automatic Query persisting with Apollo Engine
        persisting: false, // Optional
        // Use websockets for everything (no HTTP)
        // You need to pass a `wsEndpoint` for this to work
        websocketsOnly: false // Optional
      },
      test: {
        httpEndpoint: 'http://localhost:5000',
        wsEndpoint: 'http://localhost:5000',
        tokenName: 'apollo-token'
      }
    }
  }
}

Options

clientConfigs Option: required

Sets up the apollo client endpoints. All available options for each endpoint you find here

Check out official vue-apollo-cli where possible usecases are presented.

clientConfigs.default Option: required

clientConfigs. Option: optional

tokenName String: optional, default: 'apollo-token'

Token name for the cookie which will be set in case of authentication. You can also provide an option tokenName in each of your clientConfigs to overwrite the default.

authenticationType String: optional, default: 'Bearer'

Sets the authentication type for any authorized request. Modify this if its not Bearer.

includeNodeModules Boolean: optional, default: false

In case you use *.gql files inside of node_module folder you can enable the graphql-tag/loader to parse the files for you.

Usage

Once the setup is completed you have a successfully enabled vue-apollo in your project. Checkout Official example and vue-apollo how to use vue-apollo inside your application code

Authentication

You have following methods for authentication available:

 // set your graphql-token
 this.$apolloHelpers.onLogin(token, /* if not default you can pass in client as second argument */)
 // unset your graphql-token
 this.$apolloHelpers.onLogout(/* if not default you can pass in client as second argument */)
 // get your current token (we persist token in a cookie)
 this.$apolloHelpers.getToken(/* you can provide named tokenName if not 'apollo-token' */)

Check out the full example

For permanent authorization tokens the setup just provide getAuth function for each of your endpoint configurations:

  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://graphql.datocms.com',
        getAuth: () => 'Bearer your_token_string'
      },
    }
  },

User login

methods:{
  async onSubmit () {
    const credentials = this.credentials
    try {
        const res = await this.$apollo.mutate({
            mutation: authenticateUserGql,
            variables: credentials
        }).then(({data}) => data && data.authenticateUser)
        await this.$apolloHelpers.onLogin(res.token)
    } catch (e) {
        console.error(e)
    }
  },
}

User logout

methods:{
  async onLogout () {
    await this.$apolloHelpers.onLogout()
  },
}

getToken

// middleware/isAuth.js
  export default function ({app, error}) {
    const hasToken = !!app.$apolloHelpers.getToken()
    if (!hasToken) {
        error({errorCode:503, message:'You are not allowed to see this'})
    }
}

Examples to access the defaultClient of your apolloProvider

Vuex actions
export default {
  actions: {
    foo (store, payload) {
      let client = this.app.apolloProvider.defaultClient
    }
  }
}
asyncData/fetch method of page component
export default {
  asyncData (context) {
    let client = context.app.apolloProvider.defaultClient
  }
}
onServerInit
export default {
  nuxtServerInit (store, context) {
    let client = context.app.apolloProvider.defaultClient
  }
}
access client or call mutations of any method inside of component
export default {
  methods:{
    foo(){
      // receive the associated Apollo client 
      const client = this.$apollo.getClient()

      // most likely you would call mutations like following:
      this.$apollo.mutate({mutation, variables})
    }
  }
}
query on any component
export default {
  apollo: {
    foo: {
      query: fooGql,
      variables () {
        return {
          myVar: this.myVar
        }
      }
    }
  }
}

Add GQL file recognition on node_modules

  apollo: {
    clientConfigs: {
      default: '~/apollo/client-configs/default.js'
    },
    includeNodeModules: true
  }

Upgrade

Upgrade Guide apollo-module v3 => v4

Version 4 of this module leaves you with zero configuration. This means we use the best possible approach available from vue-cli-plugin-apollo and the same configuration behaviour. This means you don't need to wire up your own configuration, simply pass

Edit your configuration as following:

// nuxt.config.js
apollo:{
 clientConfigs:{
  default:{
    httpEndpoint: YOUR_ENDPOINT,
    wsEndpoint: YOUR_WS_ENDPOINT
  }
 }
}

Upgrade Guide apollo-client v1 => v2

Version 3 of this module is using apollo-client 2.x. You need to make sure to update all your middle/afterware according to the upgrade guide of apollo-client. Check this source for a reference: https://github.com/apollographql/apollo-client/blob/master/Upgrade.md

Troubleshooting

Proxies

CORS errors are most often resolved with proxies. If you see a Cross-Origin-Request error in your client side console look into setting up a proxy. Check out https://github.com/nuxt-community/proxy-module for quick and straight forward setup.

ctx.req.session - req is undefined

This is just a placeholder. You'll want to replace it with whatever storage mechanism you choose to store your token. Here is an example using local storage : vuejs/apollo#144

Contribute and wire up setup

Setup the required fields in .env file in root folder

// .env
HTTP_ENDPOINT=https://your-endpoint
WS_ENDPOINT=wss://your-endpoint

In index.vue the login process requires that the gql endpoint enables a mutation which returns a valid token:

mutation authenticateUser($email:String!,$password:String!){
    authenticateUser(email: $email, password: $password) {
        token
        id
    }
}

If your gql backend is prepared start running nuxt as follow

# npm install
# npm run dev

apollo-module's People

Contributors

atinux avatar bjunc avatar dohomi avatar ducngtuan avatar hendrixer avatar huyhong avatar igorvaryvoda avatar jarnojellesma avatar jrobber avatar kieusonlam avatar negezor avatar pepsighan avatar pschaub avatar wulfmann avatar zhanafe avatar

Stargazers

 avatar

Watchers

 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.