1

So I am connecting Prisma orm to Graphql Nexus and need to convert graphql args that are T | null | undefined to T | undefined that is accepted by Prisma.

Here is how it is done inside Nexus https://github.com/graphql-nexus/nexus-plugin-prisma/blob/6c8801c6e1d99bfdb73a7c1c89db9607712b0e01/src/null.ts

How can this be adapted to my need?

Nenad
  • 231
  • 3
  • 15
  • In this case, you can have a helper function that does the same recursively for args in a GraphQL middleware. – Ryan Jul 08 '21 at 10:40
  • @Ryan Any advice how to do it in Typescript, I can do it in JS but it will not keep types. – Nenad Jul 08 '21 at 10:59
  • I don't think types can be kept in this case as you are converting `null` to `undefined` which will break types. So you would either need to do some complex TypeScript conversion that I'm not familiar with or keep the args as any and directly pass them to Prisma. – Ryan Jul 08 '21 at 11:06

1 Answers1

2

You could do something like this

const isPlainObject = (value: unknown): value is PlainObj =>
  typeof value === "object" && value !== null && !Array.isArray(value);

export type DeNullify<T> = T extends null
  ? undefined
  : T extends { [key: string]: any }
  ? { [K in keyof T]: DeNullify<T[K]> }
  : T;

export const deNullify = <T>(src: T): DeNullify<T> => {
  if (src === null) return undefined as DeNullify<T>;
  if (isPlainObject(src)) {
    const obj = Object.create(null);
    for (const [key, value] of Object.entries(src)) {
      obj[key] = deNullify(value);
    }
    return obj;
  }
  return src;
};

const obj = deNullify({ a: 1, b: 2, c: undefined, d: null }) // { a: 1, b: 2, c: undefined, d: undefined }

Update: I ended up publishing it to NPM. You can install it npm install dnull

brielov
  • 1,887
  • 20
  • 28