graphql-codegen-typescript-fabbrica icon indicating copy to clipboard operation
graphql-codegen-typescript-fabbrica copied to clipboard

Global Transient Fields

Open mizdra opened this issue 2 years ago • 0 comments
trafficstars

Global Transient Fields can define special Transient Fields that also affects build methods called on deep stacks.

import {
  defineBookFactory,
  defineBookShelfFactory,
} from '../__generated__/fabbrica';

declare module '@mizdra/graphql-codegen-typescript-fabbrica/helper' {
  interface GlobalTransientFields {
    $user: { __typename: 'User', name: string };
  }
}

const BookFactory = defineBookFactory({
  defaultFields: {
    __typename: 'Book',
    id: dynamic(({ seq }) => `Book:${seq}`),
    title: 'old-book',
    author: dynamic(async ({ get }) => await get('$user')!),
  },
});
const BookShelfFactory = defineBookShelfFactory({
  defaultFields: {
    __typename: 'BookShelf',
    id: ({ seq }): `BookShelf:${seq}`,
    name: 'my-bookshelf',
    owner: dynamic(async ({ get }) => await get('$user')!),
    books: dynamic(async () => await BookFactory.buildList()),
  },
});

const bookShelf = BookShelfFactory.build({
  $user: { __typename: 'User', name: 'mizdra' },
});
expect(bookShelf).toStrictEqual({
  __typename: 'BookShelf',
  id: 'BookShelf:0',
  name: 'my-bookshelf',
  owner: { __typename: 'User', name: 'mizdra' },
  books: [
    {
      id: 'Book:0',
      title: 'old-book',
      author: { __typename: 'User', name: 'mizdra' },
    },
    {
      id: 'Book:1',
      title: 'old-book',
      author: { __typename: 'User', name: 'mizdra' },
    },
  ],
});

I think that https://github.com/tc39/proposal-async-context is required to implement this feature.

mizdra avatar Oct 08 '23 14:10 mizdra