Recursively convert object items that are equal to null to undefined

820 views Asked by At

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?

1

There are 1 answers

0
brielov On

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