forked from reduxjs/redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
89 lines (81 loc) · 2.51 KB
/
index.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
import { ExpressionKind, SpreadElementKind } from 'ast-types/gen/kinds';
import {
ExpressionStatement,
JSCodeshift,
ObjectExpression,
Transform,
} from 'jscodeshift';
function wrapInAddCaseExpression(
j: JSCodeshift,
addCaseArgs: (ExpressionKind | SpreadElementKind)[]
) {
const identifier = j.identifier('builder');
return j.expressionStatement(
j.callExpression(j.memberExpression(identifier, j.identifier('addCase'), false), addCaseArgs)
);
}
export function reducerPropsToBuilderExpression(j: JSCodeshift, defNode: ObjectExpression) {
const caseExpressions: ExpressionStatement[] = [];
for (let property of defNode.properties) {
let addCaseArgs: (ExpressionKind | SpreadElementKind)[] = [];
switch (property.type) {
case 'ObjectMethod': {
const { key, params, body } = property;
if (body) {
addCaseArgs = [key, j.arrowFunctionExpression(params, body)];
}
break;
}
case 'ObjectProperty': {
const { key } = property;
switch (property.value.type) {
case 'ArrowFunctionExpression':
case 'FunctionExpression': {
const { params, body } = property.value;
if (body) {
addCaseArgs = [key, j.arrowFunctionExpression(params, body)];
}
break;
}
case 'Identifier':
case 'MemberExpression': {
const { value } = property;
addCaseArgs = [key, value];
break;
}
}
}
}
if (!addCaseArgs.length) {
continue;
}
caseExpressions.push(wrapInAddCaseExpression(j, addCaseArgs));
}
return j.arrowFunctionExpression([j.identifier('builder')], j.blockStatement(caseExpressions));
}
const transform: Transform = (file, api) => {
const j = api.jscodeshift;
return (
j(file.source)
// @ts-ignore some expression mismatch
.find(j.CallExpression, {
callee: { name: 'createReducer' },
// @ts-ignore some expression mismatch
arguments: { 1: { type: 'ObjectExpression' } },
})
.forEach((path) => {
const reducerObjectExpression = path.node.arguments[1] as ObjectExpression;
j(path).replaceWith(
j.callExpression(j.identifier('createReducer'), [
path.node.arguments[0],
reducerPropsToBuilderExpression(j, reducerObjectExpression),
])
);
})
.toSource({
arrowParensAlways: true,
})
);
};
export const parser = 'tsx';
export default transform;