forked from apollographql/apollo-client
/
jscodeshift-migrate-2-to-3.js
105 lines (93 loc) · 3.15 KB
/
jscodeshift-migrate-2-to-3.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* This jscodeshift transform takes care of some of the rote
* things you'll need to do while migrating from v2 to v3.
* Currently it:
* - Replaces @apollo/react-hooks imports with
* @apollo/client
* - Removes gql imports from graphql-tag and replaces them
* with an import from @apollo/client
* - Removes Observable import from apollo-link and moves
* it to @apollo/client
*
* Author: Dmitry Minkovsky <dminkovsky@gmail.com>
*/
export default function transformer(file, api) {
const j = api.jscodeshift;
const source = j(file.source);
// Replace `apollo-client` with `@apollo/client`
renameImport('apollo-client', '@apollo/client');
// TODO: Create if @apollo/client doesn't exist.
// source.find(j.Program).replaceWith(p => ({
// ...p.value,
// body: [
// {
// type: 'ImportDeclaration',
// specifiers: specifiers.map(
// importSpecifier,
// ),
// source: {
// type: 'Literal',
// value: '@apollo/client',
// },
// },
// ...p.value.body,
// ],
// }));
moveSpecifiersToApolloClient('@apollo/react-hooks', []);
moveSpecifiersToApolloClient('apollo-cache-inmemory', ['InMemoryCache']);
moveSpecifiersToApolloClient('graphql-tag', []);
moveSpecifiersToApolloClient('apollo-link', []);
moveSpecifiersToApolloClient('apollo-link-http', []);
moveSpecifiersToApolloClient('apollo-link-http-common', []);
renameImport('@apollo/react-components', '@apollo/client/react/components');
renameImport('@apollo/react-hoc', '@apollo/client/react/hoc');
renameImport('@apollo/react-ssr', '@apollo/client/react/ssr');
renameImport('@apollo/react-testing', '@apollo/client/testing');
return source.toSource();
function moveSpecifiersToApolloClient(
moduleName,
specifiers,
) {
const moduleImport = getImport(moduleName);
moduleImport.remove();
if (moduleImport.size()) {
const clientImports = getImport('@apollo/client');
if (clientImports.size()) {
clientImports.replaceWith(p => ({
...p.value,
specifiers: [
...specifiers.map(importSpecifier),
...p.value.specifiers,
],
}));
}
}
}
function renameImport(oldModuleName, newModuleName) {
getImport(oldModuleName)
.find(j.Literal)
.replaceWith(path => ({
...path.value,
value: newModuleName,
}));
}
function getImport(moduleName) {
return source
.find(j.ImportDeclaration)
.filter(
path => path.value.source.value === moduleName,
);
}
}
function importSpecifier(name) {
return {
type: 'ImportSpecifier',
imported: {
type: 'Identifier',
name,
},
};
}
// Warn about apollo-boost?
// Warn about graphql-anywhere?
// Warn about graphql-tag?