This codemod can be used to migrate rejectOnNotFound usages to the new Prisma 4 findUniqueOrThrow
and findFirstOrThrow
methods.
Last active
July 26, 2022 03:52
-
-
Save casey-chow/296ec312f730fb3a8ed9a3a2447fb737 to your computer and use it in GitHub Desktop.
Prisma 4 Migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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