Skip to content

Instantly share code, notes, and snippets.

@casey-chow
Last active July 26, 2022 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casey-chow/296ec312f730fb3a8ed9a3a2447fb737 to your computer and use it in GitHub Desktop.
Save casey-chow/296ec312f730fb3a8ed9a3a2447fb737 to your computer and use it in GitHub Desktop.
Prisma 4 Migration

This codemod can be used to migrate rejectOnNotFound usages to the new Prisma 4 findUniqueOrThrow and findFirstOrThrow methods.

import {
API,
FileInfo,
Identifier,
MemberExpression,
ObjectExpression,
ObjectProperty,
} from "jscodeshift";
export const parser = "ts";
export default function (fileInfo: FileInfo, api: API, options: any) {
const j = api.jscodeshift;
const ast = j(fileInfo.source);
// 1. Find any keys with rejectOnNotFound
// ASSUMPTION: rejectOnNotFound is always set to true
const calls = ast
.find(j.CallExpression, (node) =>
["findUnique", "findFirst"].includes(node.callee.property?.name)
)
.filter((path) => {
// path.node.arguments?.length === 1 && path.node.arguments[0].properties
// console.log((path.node.arguments[0] as ObjectExpression).properties)
return (path.node.arguments[0] as ObjectExpression).properties.some(
(property) =>
((property as ObjectProperty).key as Identifier)?.name ===
"rejectOnNotFound"
);
});
calls.forEach((path) => {
const name = ((path.node.callee as MemberExpression).property as Identifier)
.name;
if (name === "findUnique") {
((path.node.callee as MemberExpression).property as Identifier).name =
"findUniqueOrThrow";
} else if (name === "findFirst") {
((path.node.callee as MemberExpression).property as Identifier).name =
"findFirstOrThrow";
}
});
calls
.find(
j.ObjectProperty,
(node) => node.key.name === "rejectOnNotFound"
)
.remove();
return ast.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment