dotansimha / dotansimha/graphql-code-generator
Apollo Client Helper `keyFields` type signature mismatch
- Dominant language
- TypeScript
- Stars
- 11.3k
- Forks
- 1.4k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 23
Description
**Describe the bug**
Apollo Client Helpers generates a type signature for `keyFields` that does not seem to align with Apollo Client (based on 3.5.x) and generates type errors when attempting to use a function to generate a value.
**To Reproduce**
Steps to reproduce the behavior:
1. https://codesandbox.io/s/eloquent-cohen-ngiu9?file=/base-apollo.ts demonstrates using Apollo's generic `TypePolicies` typings which does not generate an error
1. https://codesandbox.io/s/eloquent-cohen-ngiu9?file=/sig-mismatch-apollo.ts demonstrates the type error
**Error details**
```typescript
Type '(entity: any) => string' is not assignable to type 'false | UserKeySpecifier | (() => UserKeySpecifier)'.
Type '(entity: any) => string' is not assignable to type '() => UserKeySpecifier'.ts(2322)
helper.ts(18, 3): The expected type comes from property 'keyFields' which is declared here on type 'Omit & { keyFields?: false | UserKeySpecifier | (() => UserKeySpecifier); fields?: UserFieldPolicy; }'
```
**Expected behavior**
I would expect that I can define `keyFields` for a GraphQL Type as function that could return either a field from the type, `false`, or an arbitrary `string`. For example, one might use `md5` on one or more entity fields to create a hash, or joins multiple fields together with a specific delimeter.
**Possible Solution**
Experimenting locally, I was able to piece together a type from Apollo Client with a small tweak to take a generic which could be the FieldSpecificer. This approach would remove the need to generate a `KeyFieldsFunction` for each type.
```typescript
/**
* @see https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/policies.ts#L99-L102
*/
type KeyFieldsFunction = (
object: Readonly,
context: KeyFieldsContext
/**
* `(string | T)[]`
* @see https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/policies.ts#L60-L62
*/
) => (string | T)[] | false | ReturnType;
# usage
export type StrictTypedTypePolicies = {
...
User?: Omit & {
keyFields?: false | UserKeySpecifier | KeyFieldsFunction,
fields?: UserFieldPolicy,
}
};
```
**Environment:**
- OS: MacOS Monterey
- `@graphql-codegen/typescript-apollo-client-helpers`: `2.18`
- NodeJS: 16.x
**Additional context**
- Also noticed and references https://github.com/dotansimha/graphql-code-generator/discussions/4700#discussioncomment-514964
- Additional example: https://github.com/sjungling/graphql-codegen-keyfields
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.