Setup Graphql for Angular project
Thu 27 Aug 2020

Step 1. Generate schema by requesting to graphql host

Generate Graph Schema using Rubymine Plugin: https://blog.jetbrains.com/webstorm/201 9/04/featured-plugin-js-graphql/

Follow the instruction to create this file: .graphqlconfig

{
  "name": "Untitled GraphQL Schema",
  "schemaPath": "schema.graphql",
  "extensions": {
    "endpoints": {
      "Default GraphQL Endpoint": {
        "url": "http://localhost:3000/graphql",
        "headers": {
          "user-agent": "JS GraphQL"
        },
        "introspect": false
      }
    }
  }
}

Using Webstorm to generate shema as link above.

Step 2. Using Apollo with Codegen to generate typescript for queries 

Additional dependencies:

{
  "scripts": {
    "gen": "graphql-codegen --config codegen.yml"
  },
  "dependencies": {
    "@auth0/angular-jwt": "^2.0.0",
    "apollo-angular": "^1.5.0",
    "apollo-angular-link-http": "^1.3.1",
    "apollo-cache-inmemory": "^1.3.2",
    "apollo-client": "^2.4.0",
    "apollo-link": "^1.2.4",
    "apollo-link-context": "^1.0.12",
    "apollo-upload-client": "^9.1.0",
    "apollo-upload-file": "^8.0.1",
    "graphql": "^14.1.1",
    "graphql-tag": "^2.10.0"
  },
  "devDependencies": {
    "@graphql-codegen/cli": "^1.3.1",
    "@graphql-codegen/typescript": "^1.3.1",
    "@graphql-codegen/typescript-apollo-angular": "^1.3.1",
    "@graphql-codegen/typescript-operations": "^1.3.1"
  }
}

Make sure the config codegen.yml. It generate schema.graphql by querying the endpoints we setup at step 1.  It also generate typescript based on queries and mutations defined (create some files in those folders.

overwrite: true
schema: schema.graphql
documents:
  - src/queries/*.graphql
  - src/mutations/*.graphql
generates:
  src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-apollo-angular"

Create some queries or mutations in same folder.

mutations/login.graphql

mutation login($email: String!, $password: String!){
    login(email: $email, password: $password) {
        email
    }
}

Generate by yarn gen

(base) ➜  frontend yarn gen
yarn run v1.22.4
warning package.json: License should be a valid SPDX license expression
$ graphql-codegen --config codegen.yml
  ✔ Parse configuration
  ✔ Generate outputs
✨  Done in 15.67s.
(base) ➜  frontend

We've done the setup.


https://github.com/dotansimha/graphql-code-generator