Skip to content
This repository has been archived by the owner on Mar 26, 2024. It is now read-only.

feat(v1): custom declarations #303

Open
wants to merge 8 commits into
base: alpha
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,20 @@ const config: SanityCodegenConfig = {
* prevent naming collisions.
*/
// generateTypeName: undefined,
/**
* Optionally provide a function that generates the typescript workspace
* identifier from the schema type name.
*
* Please note that this identifier is used for the generated typescript
* file, so the returned value should be a valid typescript identifier.
*/
// generateWorkspaceName: undefined,
/**
*
* Custom declarations to be added to the generated types, or a function that
* returns such declarations.
*/
// declarations: undefined,
/**
* This option is fed directly to prettier `resolveConfig`
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,48 @@ const config: SanityCodegenConfig = {
{ name: 'author', type: 'string' },
],
},
{
name: 'foo',
type: 'document',
fields: [{ name: 'myStr', type: 'string' }],
},
],
}),
],
include: '**/*.{js,ts,tsx}',
generateWorkspaceName: (name) => `Overriden${name}`,
generateTypeName: (name) => (name === 'Foo' ? 'Bar' : name),
declarations: ({ t, normalizedSchemas, getWorkspaceName }) =>
normalizedSchemas.flatMap((normalizedSchema) => [
/* ts */ `
namespace Sanity.${getWorkspaceName(normalizedSchema)}.Schema {
type CustomTypeFromString = {
foo: string;
};
}
`,
t.tsModuleDeclaration(
t.identifier('Sanity'),
t.tsModuleDeclaration(
t.identifier(getWorkspaceName(normalizedSchema)),
t.tsModuleDeclaration(
t.identifier('Schema'),
t.tsModuleBlock([
t.tsTypeAliasDeclaration(
t.identifier('CustomTypeFromTSModuleDeclaration'),
undefined,
t.tsTypeLiteral([
t.tsPropertySignature(
t.identifier('foo'),
t.tsTypeAnnotation(t.tsStringKeyword()),
),
]),
),
]),
),
),
),
]),
};

export default config;
31 changes: 25 additions & 6 deletions packages/cli/src/commands/codegen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ describe('codegen command', () => {
[
"Starting codegen…",
"Using sanity-codegen config found at <PATH>",
"[default] Generating types for workspace \`default\`",
"[default] Converted 1 schema definition to TypeScript",
"[default] Generating types for workspace \`default\` as \`OverridenDefault\`",
"[default] Converted 2 schema definitions to TypeScript",
"[default] Plucking queries from files…",
"[default] Finding files to extract queries from…",
"[default] Found 2 candidate files",
Expand All @@ -63,15 +63,29 @@ describe('codegen command', () => {
[
"/// <reference types="@sanity-codegen/types" />

namespace Sanity.Default.Client {
namespace Sanity.OverridenDefault.Client {
type Config = {
QueryKey: Sanity.Default.Query.QueryKey;
QueryKey: Sanity.OverridenDefault.Query.QueryKey;
};
}
namespace Sanity.Default.Query {
namespace Sanity.OverridenDefault.Query {
type QueryKey = (string | null)[];
}
namespace Sanity.Default.Schema {
namespace Sanity.OverridenDefault.Schema {
type CustomTypeFromString = {
foo: string;
};
}
namespace Sanity.OverridenDefault.Schema {
type Bar =
| {
_id: string;
_type: "foo";
myStr?: string;
}
| undefined;
}
namespace Sanity.OverridenDefault.Schema {
type Book =
| {
_id: string;
Expand All @@ -81,6 +95,11 @@ describe('codegen command', () => {
}
| undefined;
}
namespace Sanity.OverridenDefault.Schema {
type CustomTypeFromTSModuleDeclaration = {
foo: string;
};
}
",
]
`);
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/commands/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ export default class GroqCodegen extends Command {
babelOptions,
prettierResolveConfigOptions: config?.prettierResolveConfigOptions,
prettierResolveConfigPath: config?.prettierResolveConfigPath,
generateTypeName: config?.generateTypeName,
generateWorkspaceName: config?.generateWorkspaceName,
declarations: config?.declarations,
root,
normalizedSchemas,
logger,
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/__example-files__/example-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ export const exampleSchema = [
{ name: 'description', type: 'blocks' },
],
},
{
type: 'document',
name: 'editorial',
fields: [
{ name: 'title', type: 'string' },
{ name: 'description', type: 'blocks' },
],
},
{
name: 'blocks',
type: 'array',
Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/generate-query-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ interface GenerateQueryTypesOptions {
* optionally override the default logger (e.g. to silence it, etc)
*/
logger?: Sanity.Codegen.Logger;
workspaceIdentifier?: string;
}

export function generateQueryTypes({
normalizedSchema,
extractedQueries,
workspaceIdentifier = defaultGenerateTypeName(normalizedSchema.name),
...options
}: GenerateQueryTypesOptions) {
// TODO: allow customizing this?
const workspaceIdentifier = defaultGenerateTypeName(normalizedSchema.name);

const { logger = simpleLogger } = options;
const queries = extractedQueries
.map(({ queryKey, query }) => {
Expand Down
15 changes: 10 additions & 5 deletions packages/core/src/generate-schema-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ import * as t from '@babel/types';
import { defaultGenerateTypeName } from './default-generate-type-name';
import { transformSchemaNodeToStructure } from './transform-schema-to-structure';
import { transformStructureToTs } from './transform-structure-to-ts';
import { GenerateTypesOptions } from './generate-types';

interface GenerateSchemaTypesOptions {
normalizedSchema: Sanity.SchemaDef.Schema;
workspaceIdentifier?: string;
generateTypeName?: GenerateTypesOptions['generateTypeName'];
}

export function generateSchemaTypes({
normalizedSchema,
workspaceIdentifier = defaultGenerateTypeName(normalizedSchema.name),
generateTypeName = (typeName) => typeName,
}: GenerateSchemaTypesOptions) {
// TODO: allow customizing this?
const workspaceIdentifier = defaultGenerateTypeName(normalizedSchema.name);

const topLevelSchemaNodes = [
...normalizedSchema.documents,
...normalizedSchema.registeredTypes,
Expand All @@ -24,8 +26,11 @@ export function generateSchemaTypes({
normalizedSchema,
});

// TODO: allow customizing this?
const identifier = defaultGenerateTypeName(node.name);
const identifier = generateTypeName(defaultGenerateTypeName(node.name), {
node,
nodes: topLevelSchemaNodes,
normalizedSchema,
});

const { tsType, declarations, substitutions } = transformStructureToTs({
structure,
Expand Down
Loading