Skip to content

Commit

Permalink
feat: support endpoint config (#1585)
Browse files Browse the repository at this point in the history
  • Loading branch information
vicary committed Apr 6, 2023
1 parent 39ffad9 commit f6d00c0
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 30 deletions.
42 changes: 42 additions & 0 deletions .TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# TODO

1. Fix normalization bug
1. In `example/react` there are two components, one using `selectField` with a depth of 4, and another with a depth of 2, they creates an infinite render loop. It is suspected the normalization of those responses overwrite each other.
1. Improve compat
1. [ ] Make sure existing codegen clients still works, including ditched types
1. [ ] Add tests for `graphql-ws`, `graphql-sse` and legacy subscription client
1. [ ] Make sure WebSockets in tests are closing properly
1. [ ] fetchPolicy -> cacheMode
1. [ ] Cleanup TODOs
1. Test React
1. [ ] Suspense mode should currectly pass after promise settlement
1. [ ] Suspense error boundary should reset after re-render
1. [ ] Manually test all hooks
1. [ ] Check if useDeferDispatch is really needed
1. [ ] Dependencies cleanup
1. Scoped query
1. [ ] Combine queries into a single fetch if they share the same cache, i.e. the client cache.
1. [ ] Tests
1. [ ] Restructure jest without pnpm workspaces to retain console colors
1. codegen
- [ ] Use the introspection endpoint as API endpoint by default
- [ ] New subscription client
- [ ] graphql-ws#lazy
- [ ] compat: globally accessible query, mutation and subscription (latest scope)
1. Documentations
1. Work on MDX
1. Study Tamagui's MDX structure
1. [ ] dev mode, then update live editor
1. Change of undocumented methods, major?
- `GQtyClient`#`buildAndFetchSelections`
1. [ ] Static query generation

## References

- <https://the-guild.dev/blog/fetch-for-servers>
- <https://the-guild.dev/graphql/yoga-server/v3/integrations/integration-with-cloudflare-workers>
- <https://github.com/dotansimha/graphql-yoga/tree/v3/website>
- <https://github.com/the-guild-org/>
- <https://github.com/the-guild-org/#meta---tools-we-use-to-build-our-tools>
- <https://github.com/the-guild-org/docs>
- <https://the-guild-components-storybook.vercel.app/>
5 changes: 5 additions & 0 deletions .changeset/curvy-dragons-smell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gqty/cli': minor
---

feat: Support "endpoint" in configuration
20 changes: 16 additions & 4 deletions packages/cli/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { formatPrettier } from './prettier';

const cjsRequire = globalThis.require || createRequire(import.meta.url);

export type GQtyConfig = Omit<GenerateOptions, 'endpoint'> & {
export type GQtyConfig = GenerateOptions & {
/**
* Introspection options
*/
Expand All @@ -33,8 +33,11 @@ function isStringRecord(v: unknown): v is Record<string, string> {

export const DUMMY_ENDPOINT = 'SPECIFY_ENDPOINT_OR_SCHEMA_FILE_PATH_HERE';

export const defaultConfig: Omit<Required<GQtyConfig>, 'transformSchema'> &
Pick<GQtyConfig, 'transformSchema'> = {
export const defaultConfig: Omit<
Required<GQtyConfig>,
'endpoint' | 'transformSchema'
> &
Pick<GQtyConfig, 'endpoint' | 'transformSchema'> = {
react: (() => {
try {
cjsRequire.resolve('react');
Expand All @@ -50,6 +53,7 @@ export const defaultConfig: Omit<Required<GQtyConfig>, 'transformSchema'> &
endpoint: DUMMY_ENDPOINT,
headers: {} as Record<string, string>,
},
endpoint: '/api/graphql',
destination: './src/gqty/index.ts',
subscriptions: false,
javascriptOutput: false,
Expand Down Expand Up @@ -122,6 +126,14 @@ export function getValidConfig(v: unknown): GQtyConfig {
}
break;
}
case 'endpoint': {
if (value && typeof value === 'string') {
newConfig[key] = value;
} else {
warnConfig(key, value, 'string', defaultConfig[key]);
}
break;
}
case 'introspection': {
if (isPlainObject(value)) {
const introspectionOptions: IntrospectionOptions = {};
Expand Down Expand Up @@ -262,7 +274,7 @@ export const gqtyConfigPromise: Promise<{
* @type {import("@gqty/cli").GQtyConfig}
*/
const config = ${JSON.stringify(config)};
module.exports = config;`)
);
}
Expand Down
48 changes: 22 additions & 26 deletions packages/cli/src/generate.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
ArgsDescriptions,
FieldDescription,
parseSchemaType,
ScalarsEnumsHash,
Schema,
SchemaUnionsKey,
Type,
FieldDescription,
ArgsDescriptions,
} from 'gqty';
import type {
GraphQLEnumType,
Expand Down Expand Up @@ -152,14 +152,10 @@ export async function generate(

scalarTypes ||= gqtyConfig.scalarTypes || defaultConfig.scalarTypes;
endpoint ||=
gqtyConfig.introspection?.endpoint ?? defaultConfig.introspection.endpoint;

if (
endpoint == null ||
!(endpoint.startsWith('http://') && endpoint.startsWith('https://'))
) {
endpoint = '/api/graphql';
}
gqtyConfig.endpoint ||
gqtyConfig.introspection?.endpoint ||
defaultConfig.endpoint ||
defaultConfig.introspection.endpoint;

react ??= gqtyConfig.react ?? defaultConfig.react;
preImport ??= gqtyConfig.preImport ?? defaultConfig.preImport;
Expand Down Expand Up @@ -263,7 +259,7 @@ export async function generate(
}

return comment
? `/** ${comment}
? `/** ${comment}
*/\n`
: '';
} else {
Expand Down Expand Up @@ -662,7 +658,7 @@ export async function generate(

acum += `
${addDescription(typeName)}export interface ${typeName} {
${addDescription(typeName)}export interface ${typeName} {
__typename?: ${
interfaceOrUnionsObjectTypes
? interfaceOrUnionsObjectTypes.map((v) => `"${v}"`).join(' | ')
Expand Down Expand Up @@ -781,7 +777,7 @@ export async function generate(
export type MakeNullable<T> = {
[K in keyof T]: T[K] | undefined;
};
export interface ScalarsEnums extends MakeNullable<Scalars> {
${deps.sortBy(enumsNames).reduce((acum, enumName) => {
acum += `${enumName}: ${enumName} | undefined;`;
Expand Down Expand Up @@ -815,7 +811,7 @@ export async function generate(
});
const json = await response.json();
return json;
};
`;
Expand Down Expand Up @@ -888,7 +884,7 @@ export const generatedSchema = {${generatedSchemaCodeString}};
// Set this flag as "true" if your usage involves React Suspense
// Keep in mind that you can overwrite it in a per-hook basis
suspense: false,
// Set this flag based on your needs
staleWhileRevalidate: false
}
Expand All @@ -909,7 +905,7 @@ export const generatedSchema = {${generatedSchemaCodeString}};
${subscriptions ? 'useSubscription,' : ''}
} = reactClient;
export {
export {
graphql,
useQuery,
usePaginatedQuery,
Expand Down Expand Up @@ -944,13 +940,13 @@ export const generatedSchema = {${generatedSchemaCodeString}};
// Set this flag as "true" if your usage involves React Suspense
// Keep in mind that you can overwrite it in a per-hook basis
suspense: false,
// Set this flag based on your needs
staleWhileRevalidate: false
}
});
export {
export {
graphql,
useQuery,
usePaginatedQuery,
Expand Down Expand Up @@ -981,7 +977,7 @@ export const generatedSchema = {${generatedSchemaCodeString}};
: ''
}
${isJavascriptOutput ? '' : 'import type { QueryFetcher } from "gqty";'}
import { createClient } from "gqty";
import { createClient } from 'gqty';
${
isJavascriptOutput
? ''
Expand All @@ -995,7 +991,7 @@ export const generatedSchema = {${generatedSchemaCodeString}};
${
subscriptions
? `
const subscriptionsClient =
const subscriptionsClient =
typeof window !== "undefined" ?
createSubscriptionsClient({
wsEndpoint: () => {
Expand All @@ -1015,18 +1011,18 @@ export const generatedSchema = {${generatedSchemaCodeString}};
'import("gqty").GQtyClient<import("./schema.generated").GeneratedSchema>'
)}export const client = createClient({
schema: generatedSchema,
scalarsEnumsHash,
scalarsEnumsHash,
queryFetcher
${subscriptions ? ', subscriptionsClient' : ''}
});`
: `export const client = createClient<GeneratedSchema, SchemaObjectTypesNames, SchemaObjectTypes>({
schema: generatedSchema,
scalarsEnumsHash,
: `export const client = createClient<GeneratedSchema, SchemaObjectTypesNames, SchemaObjectTypes>({
schema: generatedSchema,
scalarsEnumsHash,
queryFetcher
${subscriptions ? ', subscriptionsClient' : ''}
});`
}
const { query, mutation, mutate, subscription, resolved, refetch, track } = client;
Expand Down
1 change: 1 addition & 0 deletions packages/cli/test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ test('completely invalid config', () => {
"endpoint": "SPECIFY_ENDPOINT_OR_SCHEMA_FILE_PATH_HERE",
"headers": {}
},
"endpoint": "/api/graphql",
"destination": "./src/gqty/index.ts",
"subscriptions": false,
"javascriptOutput": false,
Expand Down

1 comment on commit f6d00c0

@vercel
Copy link

@vercel vercel bot commented on f6d00c0 Apr 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

gqty – ./

gqty-git-main-gqty.vercel.app
gqty.dev
gqty.vercel.app
www.gqty.dev
gqty-gqty.vercel.app

Please sign in to comment.