Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
pmelab committed Jan 17, 2024
1 parent 3a5f354 commit 8325b68
Show file tree
Hide file tree
Showing 14 changed files with 80 additions and 347 deletions.
15 changes: 12 additions & 3 deletions apps/website/gatsby-node.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { graphql, isDefined } from '@amazeelabs/gatsby-plugin-operations';
import { graphqlQuery } from '@amazeelabs/gatsby-plugin-operations';
import { IndexPagesQuery, ListPagesQuery, Locale } from '@custom/schema';
import { cpSync } from 'fs';
import { resolve } from 'path';
Expand All @@ -17,6 +17,15 @@ export const onCreateWebpackConfig = ({ actions }) => {
});
};

/**
* @template T extends any
* @param {T | undefined | null} val
* @returns {val is T}
*/
function isDefined(val) {
return Boolean(val);
}

/**
*
* @type {import('gatsby').GatsbyNode['createPages']}
Expand All @@ -36,7 +45,7 @@ export const createPages = async ({ actions }) => {
});

// Run the query that lists all pages, both decap and Drupal.
const pages = await graphql(ListPagesQuery);
const pages = await graphqlQuery(ListPagesQuery);

// Create a gatsby page for each of these pages.
pages.data?.allPages?.filter(isDefined).forEach(({ id, path, locale }) => {
Expand All @@ -52,7 +61,7 @@ export const createPages = async ({ actions }) => {
});

// Search for index page settings.
const settings = await graphql(IndexPagesQuery);
const settings = await graphqlQuery(IndexPagesQuery);

if (settings.errors) {
settings.errors.map((e) => console.error(e));
Expand Down
2 changes: 1 addition & 1 deletion apps/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"name": "@custom/website",
"private": true,
"dependencies": {
"@amazeelabs/gatsby-plugin-operations": "workspace:*",
"@amazeelabs/bridge-gatsby": "^1.2.7",
"@amazeelabs/cloudinary-responsive-image": "^1.6.15",
"@amazeelabs/gatsby-plugin-operations": "workspace:*",
"@amazeelabs/gatsby-silverback-cloudinary": "^1.2.7",
"@amazeelabs/gatsby-source-silverback": "^1.13.10",
"@amazeelabs/publisher": "^2.4.17",
Expand Down
4 changes: 2 additions & 2 deletions apps/website/src/layouts/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { graphql, useStaticQuery } from '@amazeelabs/gatsby-plugin-operations';
import { FrameQuery, registerExecutor } from '@custom/schema';
import { IntlProvider } from '@custom/ui/intl';
import { Frame } from '@custom/ui/routes/Frame';
import { graphqlOperation, useStaticOperation } from 'gatsby';
import React, { PropsWithChildren } from 'react';

export default function Layout({
Expand All @@ -10,7 +10,7 @@ export default function Layout({
}: PropsWithChildren<{
locale: string;
}>) {
const data = useStaticOperation(graphqlOperation(FrameQuery));
const data = useStaticQuery(graphql(FrameQuery));
registerExecutor(FrameQuery, data);
return (
<IntlProvider locale={locale || 'en'}>
Expand Down
5 changes: 3 additions & 2 deletions apps/website/src/pages/404.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import { graphql } from '@amazeelabs/gatsby-plugin-operations';
import {
NotFoundPageQuery,
registerExecutor,
ViewPageQuery,
} from '@custom/schema';
import { Page } from '@custom/ui/routes/Page';
import { graphqlOperation, PageProps } from 'gatsby';
import { PageProps } from 'gatsby';
import React from 'react';

import {
LanguageNegotiator,
LanguageNegotiatorContent,
} from '../utils/language-negotiator';

export const query = graphqlOperation(NotFoundPageQuery);
export const query = graphql(NotFoundPageQuery);

function isTruthy<T>(value: T | undefined | null): value is T {
return Boolean(value);
Expand Down
5 changes: 3 additions & 2 deletions apps/website/src/templates/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { graphql } from '@amazeelabs/gatsby-plugin-operations';
import {
Locale,
PageListEntryFragment,
registerExecutor,
ViewPageQuery,
} from '@custom/schema';
import { Page } from '@custom/ui/routes/Page';
import { graphqlOperation, HeadProps, PageProps } from 'gatsby';
import { HeadProps, PageProps } from 'gatsby';
import React from 'react';

export const query = graphqlOperation(ViewPageQuery);
export const query = graphql(ViewPageQuery);

export function Head({ data }: HeadProps<typeof query>) {
return data.page ? (
Expand Down
10 changes: 4 additions & 6 deletions apps/website/src/types/operations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,14 @@ import {
OperationVariables,
} from '@custom/schema';

declare module 'gatsby' {
export const graphqlOperation: <OperationId extends AnyOperationId>(
declare module '@amazeelabs/gatsby-plugin-operations' {
export const graphql: <OperationId extends AnyOperationId>(
id: OperationId,
) => OperationResult<OperationId>;

function useStaticOperation<Input extends any>(id: Input): Input;
}
function useStaticQuery<Input extends any>(id: Input): Input;

declare module '@amazeelabs/gatsby-plugin-operations' {
function graphql<OperationId extends AnyOperationId>(
function graphqlQuery<OperationId extends AnyOperationId>(
id: OperationId,
vars?: OperationVariables<OperationId>,
): Promise<{
Expand Down
31 changes: 14 additions & 17 deletions packages/gatsby-plugin-operations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,14 @@ import {
OperationVariables,
} from '@custom/schema';

declare module 'gatsby' {
export const graphqlOperation: <OperationId extends AnyOperationId>(
declare module '@amazeelabs/gatsby-plugin-operations' {
export const graphql: <OperationId extends AnyOperationId>(
id: OperationId,
) => OperationResult<OperationId>;

function useStaticOperation<Input extends any>(id: Input): Input;
}
function useStaticQuery<Input extends any>(id: Input): Input;

declare module '@amazeelabs/gatsby-plugin-operations' {
function graphql<OperationId extends AnyOperationId>(
function graphqlQuery<OperationId extends AnyOperationId>(
id: OperationId,
vars?: OperationVariables<OperationId>,
): Promise<{
Expand All @@ -61,10 +59,10 @@ The query variable can be used directly to infer the template components
properties.

```typescript
import { graphqlOperation } from 'gatsby';
import { graphql } from '@amazeelabs/gatsby-plugin-operations';
import { ViewPageQuery } from '@custom/schema';

export const query = graphqlOperation(ViewPageQuery);
export const query = graphql(ViewPageQuery);
export default function Page({
data,
pageContext,
Expand All @@ -75,28 +73,27 @@ export default function Page({

### In static queries

To run a static query, one can use `graphqlOperation` in combination with
`useStaticOperation`. This will yield a fully typed result of the requested
query.
To run a static query, one can use `graphql` in combination with
`useStaticQuery`. This will yield a fully typed result of the requested query.

```typescript
import { useStaticOperation, graphqlOperation } from 'gatsby';
import { useStaticQuery, graphql } from '@amazeelabs/gatsby-plugin-operations';
import { ListProductsQuery } from '@custom/schema';

const myResult = useStaticOperation(graphqlOperation(ListProductsQuery));
const myResult = useStaticQuery(graphql(ListProductsQuery));
```

### In `gatsby-node.mjs`

The `@amazeelabs/gatsby-plugin-operations` package directly exports a `graphql`
The `@amazeelabs/gatsby-plugin-operations` package provides a `graphqlQuery`
function that works within the `createPages` hook.

```typescript
import {graphql} from '@amazeelabs/gatsby-plugin-operations';
import {ListPagesQuery} from '@custom/schema';
import { graphqlQuery } from '@amazeelabs/gatsby-plugin-operations';
import { ListPagesQuery } from '@custom/schema';

export const createPages({actions}) {
const result = await graphql(ListPagesQuery);
const result = await graphqlQuery(ListPagesQuery);
result.page.forEach((page) => {
actions.createPage({});
})
Expand Down
3 changes: 0 additions & 3 deletions packages/gatsby-plugin-operations/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@
"vitest": "^1.1.0",
"gatsby": ">= 5"
},
"peerDependencies": {
"gatsby": ">= 5"
},
"dependencies": {
"@babel/core": "^7.23.6"
}
Expand Down
4 changes: 2 additions & 2 deletions packages/gatsby-plugin-operations/src/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync } from 'fs';
import { CreatePagesArgs } from 'gatsby';
import type { CreatePagesArgs } from 'gatsby';

export let _graphql: CreatePagesArgs['graphql'] | undefined = undefined;
let _operations: Record<string, string> | undefined = undefined;
Expand All @@ -18,7 +18,7 @@ export function initialize(
/**
* Execute a graphql query against gatsby.
*/
export function graphql(id: string, vars: any): any {
export function graphqlQuery(id: string, vars?: any): any {
if (!_graphql) {
throw '_graphql has not been initialized';
}
Expand Down
3 changes: 1 addition & 2 deletions packages/gatsby-plugin-operations/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export { graphql } from './graphql';
export { isDefined } from './utils';
export { graphqlQuery } from './graphql';
12 changes: 6 additions & 6 deletions packages/gatsby-plugin-operations/src/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ pluginTester({
title: 'Page query',
code: `
import { MyOperation } from '@custom/schema';
import { graphqlOperation } from 'gatsby';
export const query = graphqlOperation(MyOperation);
import { graphql } from '@amazeelabs/gatsby-plugin-operations';
export const query = graphql(MyOperation);
`,
output: `
import { MyOperation } from '@custom/schema';
Expand All @@ -34,9 +34,9 @@ export const query = graphql\`
title: 'Static query',
code: `
import { MyOperation } from '@custom/schema';
import { graphqlOperation, useStaticOperation } from 'gatsby';
import { graphql, useStaticQuery } from '@amazeelabs/gatsby-plugin-operations';
function useData() {
return useStaticOperation(graphqlOperation(MyOperation));
return useStaticQuery(graphql(MyOperation));
}`,
output: `
import { MyOperation } from '@custom/schema';
Expand All @@ -55,9 +55,9 @@ function useData() {
title: 'Typescript',
code: `
import { MyOperation } from '@custom/schema';
import { graphqlOperation, useStaticOperation } from 'gatsby';
import { graphql, useStaticQuery } from '@amazeelabs/gatsby-plugin-operations';
function useData() {
return useStaticOperation(graphqlOperation(MyOperation));
return useStaticQuery(graphql(MyOperation));
}
export function Component(props: { message: string }) {
Expand Down
60 changes: 6 additions & 54 deletions packages/gatsby-plugin-operations/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,6 @@
import { PluginObj, PluginPass, types } from '@babel/core';
import {
ImportDefaultSpecifier,
ImportNamespaceSpecifier,
ImportSpecifier,
} from '@babel/types';
import { readFileSync } from 'fs';

function hasImport(
specifiers: Array<
ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier
>,
name: string,
) {
return specifiers.filter((spec) => spec.local.name === name).length > 0;
}

function loadOperations(path: string) {
const loadedOperations: Record<string, string> = {};
const loaded = JSON.parse(readFileSync(path).toString());
Expand All @@ -27,46 +13,21 @@ function loadOperations(path: string) {
export default () =>
({
visitor: {
Identifier(path) {
if (path.node.name === 'graphqlQuery') {
path.replaceWith(types.identifier('graphql'));
path.skip();
}
},
ImportDeclaration(path) {
if (path.node.source.value === 'gatsby') {
const specifiers = path.node.specifiers.filter(
(spec) =>
!['graphqlOperation', 'useStaticOperation'].includes(
spec.local.name,
),
);
if (hasImport(path.node.specifiers, 'graphqlOperation')) {
specifiers.push(
types.importSpecifier(
types.identifier('graphql'),
types.identifier('graphql'),
),
);
}
if (hasImport(path.node.specifiers, 'useStaticOperation')) {
specifiers.push(
types.importSpecifier(
types.identifier('useStaticQuery'),
types.identifier('useStaticQuery'),
),
);
}
if (path.node.source.value === '@amazeelabs/gatsby-plugin-operations') {
path.replaceWith(
types.importDeclaration(specifiers, path.node.source),
types.importDeclaration(
path.node.specifiers,
types.stringLiteral('gatsby'),
),
);
path.skip();
}
},
CallExpression(path, { opts }) {
const operations = loadOperations(opts.operations);
if (path.node.callee.type === 'Identifier') {
if (path.node.callee.name === 'graphqlOperation') {
if (path.node.callee.name === 'graphql') {
if (
!(
path.node.arguments.length === 1 &&
Expand All @@ -91,15 +52,6 @@ export default () =>
path.skip();
return;
}

if (path.node.callee.name === 'useStaticOperation') {
path.replaceWith(
types.callExpression(
types.identifier('useStaticQuery'),
path.node.arguments,
),
);
}
}
},
},
Expand Down
10 changes: 0 additions & 10 deletions packages/gatsby-plugin-operations/src/utils.ts

This file was deleted.

Loading

0 comments on commit 8325b68

Please sign in to comment.