Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support customer account API in hydrogen-codegen #1569

Merged
merged 7 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/hydrogen-codegen/src/defaults.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {
GENERATED_MUTATION_INTERFACE_NAME,
GENERATED_QUERY_INTERFACE_NAME,
} from './plugin';
frandiox marked this conversation as resolved.
Show resolved Hide resolved

const sfapiDefaultInterfaceExtensionCode = `
declare module '@shopify/hydrogen' {
interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}
interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}
}`;

const caapiDefaultInterfaceExtensionCode = `
declare module '@shopify/hydrogen' {
interface CustomerAccountQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}
interface CustomerAccountMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}
}`;

const defaultValues = Object.freeze({
sfapi: {
importTypesFrom: '@shopify/hydrogen/storefront-api-types',
namespacedImportName: 'StorefrontAPI',
interfaceExtensionCode: sfapiDefaultInterfaceExtensionCode,
},
caapi: {
importTypesFrom: '@shopify/hydrogen/customer-account-api-types',
namespacedImportName: 'CustomerAccountAPI',
interfaceExtensionCode: caapiDefaultInterfaceExtensionCode,
},
});

export const getDefaultOptions = (target: keyof typeof defaultValues) =>
defaultValues[target];
19 changes: 9 additions & 10 deletions packages/hydrogen-codegen/src/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as addPlugin from '@graphql-codegen/add';
import * as typescriptPlugin from '@graphql-codegen/typescript';
import * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';
import {processSources} from './sources.js';
import {getDefaultOptions} from './defaults.js';
import {
plugin as dtsPlugin,
GENERATED_MUTATION_INTERFACE_NAME,
Expand Down Expand Up @@ -39,12 +40,6 @@ export type HydrogenPresetConfig = {
}) => string;
};

export const defaultInterfaceExtensionCode = `
declare module '@shopify/hydrogen' {
interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}
interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}
}`;

export const preset: Types.OutputPreset<HydrogenPresetConfig> = {
buildGeneratesSection: (options) => {
if (!options.baseOutputDir.endsWith('.d.ts')) {
Expand All @@ -63,18 +58,22 @@ export const preset: Types.OutputPreset<HydrogenPresetConfig> = {
const sourcesWithOperations = processSources(options.documents);
const sources = sourcesWithOperations.map(({source}) => source);

const defaultOptions = getDefaultOptions(
/^(customer|caapi\.)/i.test(options.baseOutputDir) ? 'caapi' : 'sfapi',
);

const importTypes = options.presetConfig.importTypes ?? true;
const namespacedImportName =
options.presetConfig.namespacedImportName ?? 'StorefrontAPI';
options.presetConfig.namespacedImportName ??
defaultOptions.namespacedImportName;
const importTypesFrom =
options.presetConfig.importTypesFrom ??
'@shopify/hydrogen/storefront-api-types';
options.presetConfig.importTypesFrom ?? defaultOptions.importTypesFrom;

const interfaceExtensionCode =
options.presetConfig.interfaceExtension?.({
queryType: GENERATED_QUERY_INTERFACE_NAME,
mutationType: GENERATED_MUTATION_INTERFACE_NAME,
}) ?? defaultInterfaceExtensionCode;
}) ?? defaultOptions.interfaceExtensionCode;

const pluginMap = {
...options.pluginMap,
Expand Down
27 changes: 22 additions & 5 deletions packages/hydrogen-codegen/src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
// This comment is used during ESM build:
//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);
export const getSchema = () =>
require.resolve('@shopify/hydrogen-react/storefront.schema.json');

let staticSchema = '';
/**
* Resolves a schema path for the provided API type. Only the API types currently
* bundled in Hydrogen are allowed: "storefront" and "customer".
* @param api
* @returns
*/
export const getSchema = (api = 'storefront' as 'storefront' | 'customer') => {
if (api !== 'storefront' && api !== 'customer') {
throw new Error(
`The provided API type "${api}" is unknown. Please use "storefront" or "customer".`,
);
}

return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);
};

let staticSFAPISchema = '';

try {
staticSchema = getSchema();
staticSFAPISchema = getSchema('storefront');
} catch (error) {
// This can happen at build time or when '@shopify/hydrogen-react' is not found.
// Generally this shouldn't be an issue in real apps so let's ignore the error.
// Also, this package could be used in non-Hydrogen apps.
}

export const schema = staticSchema;
/**
* The resolved schema path for the Storefront API.
*/
export const schema = staticSFAPISchema;
6 changes: 4 additions & 2 deletions packages/hydrogen-codegen/tests/codegen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ describe('Hydrogen Codegen', async () => {
// Patch dependency before importing the Codegen CLI
await import('../src/patch.js');
const {preset, schema, pluckConfig} = await import('../src/index.js');
const {defaultInterfaceExtensionCode} = await import('../src/preset.js');
const {getDefaultOptions} = await import('../src/defaults.js');
const {executeCodegen} = await import('@graphql-codegen/cli');

const getCodegenOptions = (fixture: string, output = 'out.d.ts') => ({
Expand Down Expand Up @@ -64,7 +64,9 @@ describe('Hydrogen Codegen', async () => {
);

// Augments query/mutation types
expect(generatedCode).toMatch(defaultInterfaceExtensionCode);
expect(generatedCode).toMatch(
getDefaultOptions('sfapi').interfaceExtensionCode,
);

expect(generatedCode).toMatchInlineSnapshot(`
"/* eslint-disable eslint-comments/disable-enable-pair */
Expand Down
Loading