-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-add-missing-path-param.codeshift.js
76 lines (64 loc) · 2.26 KB
/
3-add-missing-path-param.codeshift.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Prompt:
* Thank you. Now each of the handler functions might have defined generics like this:
const handlers = http.post<{
playlistItems: {
id?: number
resource: number
score: number
origin: OriginLink
}[]
}>(...)
If the function call is http.post or http.patch or http.delete, then the generics should be rewritten from the above to add a PathParamss before the original generic object like this:
const handlers = http.post<PathParam, {
playlistItems: {
id?: number
resource: number
score: number
origin: OriginLink
}[]
}>(...)
Write a JScodemod that goes through the handlers in a file and fixes this
*/
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
// A list of http methods that need to be modified
const httpMethods = ["post", "patch", "delete","put"];
// Helper function to check if the CallExpression is an http method we care about
const isHttpMethodCall = (call) => {
return (
call.callee.type === "MemberExpression" &&
call.callee.object.name === "http" &&
httpMethods.includes(call.callee.property.name)
);
};
// Find all function calls that match http.post, http.patch, or http.delete
root
.find(j.CallExpression)
.filter((path) => isHttpMethodCall(path.node))
.forEach((path) => {
const callExpression = path.node;
// Check if there are generics specified
if (
callExpression.typeParameters &&
callExpression.typeParameters.params.length > 0
) {
const firstGenericType = callExpression.typeParameters.params[0];
// Check if PathParams is already present
const alreadyHasPathParams =
firstGenericType.type === "TSTypeReference" &&
firstGenericType.typeName.name === "PathParams";
if (!alreadyHasPathParams) {
// Add PathParams as the first generic parameter
const newGenericParams = [
j.tsTypeReference(j.identifier("PathParams")),
...callExpression.typeParameters.params,
];
// Replace the original generics with the new one
callExpression.typeParameters.params = newGenericParams;
}
}
});
return root.toSource();
};