Skip to content

Instantly share code, notes, and snippets.

@nrdobie
Last active May 5, 2024 18:08
Show Gist options
  • Save nrdobie/c8255815b0083acf98be3e84bfd7c8a8 to your computer and use it in GitHub Desktop.
Save nrdobie/c8255815b0083acf98be3e84bfd7c8a8 to your computer and use it in GitHub Desktop.
Use CUID2 with Prisma

This will automatically use CUID2 for all id fields when creating elements in Prisma.

You'll need to add the following libraries to make this work

npm install --save @paralleldrive/cuid2 immer
yarn add @paralleldrive/cuid2 immer
pnpm add @paralleldrive/cuid2 immer

Immer is use to ensure that there are no side-effects when modifying the arguments.

import { createId } from "@paralleldrive/cuid2";
import { Prisma } from "@prisma/client";
import { produce } from "immer";
const cuid2Extension = Prisma.defineExtension({
name: "cuid2",
query: {
$allModels: {
create({ query, args }) {
const argsWithNewId = produce(args, (draft) => {
if (!draft.data.id) {
draft.data.id = createId();
}
});
return query(argsWithNewId);
},
createMany({ query, args }) {
const argsWithNewIds = produce(args, (draft) => {
if (Array.isArray(draft.data)) {
draft.data = draft.data.map((item) => {
if (!item.id) {
item.id = createId();
}
return item;
}) as typeof draft.data;
} else {
if (draft.data.id) {
draft.data.id = createId();
}
}
});
return query(argsWithNewIds);
},
},
},
});
export default cuid2Extension;
import { PrismaClient } from "@prisma/client";
import cuid2Extension from "./cuid2-extension";
const prismaClient = new PrismaClient().$extends(cuid2Extension);
export default prismaClient;
@joelrb
Copy link

joelrb commented May 5, 2024

Thank you for this. Great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment