Skip to content

Using the CoCore API from TypeScript

To assist TypeScript developers in integrating with the CoCore GraphQL API, here's a comprehensive guide utilizing the Apollo Client library.

1. Install Apollo Client and Dependencies

Begin by installing the necessary packages:

bash
npm install @apollo/client graphql

2. Set Up Apollo Client

Create an instance of ApolloClient pointing to your GraphQL endpoint and include the API key for authentication:

typescript
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';

const client = new ApolloClient({
  link: new HttpLink({
    uri: '$MY_COCORE_URL/graphql',
    headers: {
      Authorization: 'Bearer YOUR_API_KEY',
    },
  }),
  cache: new InMemoryCache(),
});

3. Define GraphQL Queries

Utilize the gql template literal to define your GraphQL queries or mutations. Here's an example of a query to fetch job information:

typescript
import { gql } from '@apollo/client';

const GET_JOB = gql`
  query GetJob($id: ID!) {
    job(id: $id) {
      id
      name
      quantity
    }
  }
`;

4. Execute Queries and Handle Responses

Use the client.query method to execute the query and process the response:

typescript
client
  .query({
    query: GET_JOB,
    variables: { id: 'job-id' },
  })
  .then((response) => {
    const job = response.data.job;
    console.log(`Name: ${job.name}, Quantity: ${job.quantity}`);
  })
  .catch((error) => {
    console.error('Error fetching job:', error);
  });

5. Generate TypeScript Types (Optional but Recommended)

To enhance type safety, you can generate TypeScript types based on your GraphQL schema using the GraphQL Code Generator:

  • Install the necessary packages:

    bash
    npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations
  • Create a codegen.yml configuration file:

    yaml
    schema: '$MY_COCORE_URL/graphql'
    documents: './src/**/*.ts'
    generates:
      ./src/generated/graphql.ts:
        plugins:
          - 'typescript'
          - 'typescript-operations'
  • Add a script to your package.json:

    json
    {
      "scripts": {
        "generate": "graphql-codegen"
      }
    }
  • Run the code generation:

    bash
    npm run generate

This process will create TypeScript definitions for your GraphQL operations, enabling better type safety and autocompletion in your development environment.

6. Explore API Documentation

For detailed information on available queries, mutations, and schema definitions, refer to the CoCore API documentation at https://docs.wearecococo.com.

By following these steps, TypeScript developers can effectively integrate with the CoCore GraphQL API using Apollo Client.

Connect. Combine. Collaborate.
The pioneering open integration platform, dedicated to transforming connectivity in the printing industry.