New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@shopify/api-codegen-preset

Package Overview
Dependencies
Maintainers
0
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@shopify/api-codegen-preset

Preset for graphql-codegen to parse and type queries to Shopify APIs

  • 1.1.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
25K
decreased by-18.57%
Maintainers
0
Weekly downloads
 
Created
Source

@shopify/api-codegen-preset

License: MIT npm version

This package enables JavaScript / TypeScript apps to use a #graphql tag to parse queries with graphql-codegen.

It produces TypeScript types for every query picked up by your codegen configuration. Shopify's clients are then able to use those types to automatically type your operation's variables and return types.

Getting started

The first step is to install the @shopify/api-codegen-preset package, using your preferred package manager:

yarn add --dev @shopify/api-codegen-preset
npm add --save-dev @shopify/api-codegen-preset
pnpm add -D @shopify/api-codegen-preset

Configuration

This package provides 3 key exports, that make it increasingly easier to set up a project:

  1. preset: provides the low-level implementation that converts the schema into types. Include this in a generates step.
  2. shopifyApiTypes: provides all the generates steps needed for a project.
  3. shopifyApiProject: one-stop-shop setup for an entire codegen project.

preset

Use this as a Codegen preset inside a generates step. This gives you complete control over your configuration if you want to set up a fully custom scenario.

OptionTypeDefaultDescription
apiTypeApiTypeN/AThe API to pull schemas from.
modulestring?Depends on ApiTypeChange the module whose types will be overridden. Use this to override the types for any package, as long as it uses the same names.

[!TIP] You can also set your codegen configuration to output .ts files, instead of .d.ts. That may slightly increase build sizes, but it enables you to import enums from the schema in your app code.

Example .graphqlrc.ts file
import {ApiType, pluckConfig, preset} from '@shopify/api-codegen-preset';

export default {
  // For syntax highlighting / auto-complete when writing operations
  schema: 'https://shopify.dev/admin-graphql-direct-proxy',
  documents: ['./**/*.{js,ts,jsx,tsx}'],
  projects: {
    default: {
      // For type extraction
      schema: 'https://shopify.dev/admin-graphql-direct-proxy',
      documents: ['./**/*.{js,ts,jsx,tsx}'],
      extensions: {
        codegen: {
          // Enables support for `#graphql` tags, as well as `/* GraphQL */`
          pluckConfig,
          generates: {
            './types/admin.schema.json': {
              plugins: ['introspection'],
              config: {minify: true},
            },
            './types/admin.types.d.ts': {
              plugins: ['typescript'],
            },
            './types/admin.generated.d.ts': {
              preset,
              presetConfig: {
                apiType: ApiType.Admin,
              },
            },
          },
        },
      },
    },
  },
};

shopifyApiTypes

This function creates the appropriate generates steps for a project. Use this function if you want to configure a custom project, or add your own generates steps.

OptionTypeDefaultDescription
apiTypeApiTypeN/AThe API to pull schemas from.
apiVersionstring?Oldest stable versionPull schemas for a specific version.
apiKeystring?N/AThe app's API key. This can be found in the app's page in Shopify Partners in the "Authentication" section. Required and only valid for the customer API preset and helpers for now
outputDirstring?.Where to output the types files.
documentsstring[]?./**/*.{ts,tsx}Glob pattern for files to parse.
modulestring?Depends on ApiTypeChange the module whose types will be overridden. Use this to override the types for any package, as long as it uses the same names.
declarationsboolean?trueWhen true, create declaration (.d.ts) files with the types. When false, creates .ts files that can be imported in app code. May slightly increase build sizes.
Example .graphqlrc.ts file
import {
  ApiType,
  pluckConfig,
  shopifyApiTypes,
} from '@shopify/api-codegen-preset';

export default {
  // For syntax highlighting / auto-complete when writing operations
  schema: 'https://shopify.dev/admin-graphql-direct-proxy/2023-10',
  documents: ['./app/**/*.{js,ts,jsx,tsx}'],
  projects: {
    // To produce variable / return types for Admin API operations
    schema: 'https://shopify.dev/admin-graphql-direct-proxy/2023-10',
    documents: ['./app/**/*.{js,ts,jsx,tsx}'],
    extensions: {
      codegen: {
        pluckConfig,
        generates: shopifyApiTypes({
          apiType: ApiType.Admin,
          apiVersion: '2023-10',
          documents: ['./app/**/*.{js,ts,jsx,tsx}'],
          outputDir: './app/types',
        }),
      },
    },
  },
};

shopifyApiProject

This function creates a fully-functional project configuration.

OptionTypeDefaultDescription
apiTypeApiTypeN/AThe API to pull schemas from.
apiVersionstring?Oldest stable versionPull schemas for a specific version.
outputDirstring?.Where to output the types files.
documentsstring[]?./**/*.{ts,tsx}Glob pattern for files to parse.
modulestring?Depends on ApiTypeChange the module whose types will be overridden. Use this to override the types for any package, as long as it uses the same names.
declarationsboolean?trueWhen true, create declaration (.d.ts) files with the types. When false, creates .ts files that can be imported in app code. May slightly increase build sizes.
Example .graphqlrc.ts file
import {shopifyApiProject, ApiType} from '@shopify/api-codegen-preset';

export default {
  // For syntax highlighting / auto-complete when writing operations
  schema: 'https://shopify.dev/admin-graphql-direct-proxy/2023-10',
  documents: ['./app/**/*.{js,ts,jsx,tsx}'],
  projects: {
    // To produce variable / return types for Admin API operations
    default: shopifyApiProject({
      apiType: ApiType.Admin,
      apiVersion: '2023-10',
      documents: ['./app/**/*.{js,ts,jsx,tsx}'],
      outputDir: './app/types',
    }),
  },
};

Generating types

Once you configure your app, you can run graphql-codegen to start parsing your queries for types.

To do that, add this script to your package.json file:

{
  "scripts": {
    // ...
    "graphql-codegen": "graphql-codegen"
  }
}

You can then run the script using your package manager:

yarn graphql-codegen
npm run graphql-codegen
pnpm graphql-codegen

[!NOTE] Codegen will fail if it can't find any documents to parse. To fix that, either create a query or set the ignoreNoDocuments option to true. Queries and mutations must have a name for the parsing to work.

Once the script parses your operations, you can mark any operations for parsing by adding the #graphql tag to the string. For example:

import '../types/admin.generated.d.ts';

const response = await myGraphqlClient.graphql(
  `#graphql
  query getProducts($first: Int!) {
    products(first: $first) {
      edges {
        node {
          id
          handle
        }
      }
    }
  }`,
  {
    variables: {
      first: 1,
    } as GetProductsQueryVariables,
  },
);

const data: GetProductsQuery = response.data;

You'll note that once the script parses this query, the admin.generated.d.ts file will start including a new GetProductsQuery type that maps to your query.

You can commit these types to your repository, so that you don't have to re-run the parsing script every time.

To make your development flow faster, you can pass in the --watch flag to update the query types whenever you save a file:

npm run graphql-codegen -- --watch

Keywords

FAQs

Package last updated on 07 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc