-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
204 lines (173 loc) · 5.92 KB
/
main.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env node
const { getIntrospectionQuery } = require("graphql");
const { clientMutationId, mutationTypeName, primaryKey, GqlKinds } = require('./constants')
const fetch = require("node-fetch");
const commandLineArgs = require("command-line-args");
const changeCase = require("change-case");
const chalk = require("chalk");
const prettier = require("prettier");
const fs = require("fs");
const optionDefinitions = [
{ name: "table", alias: "t", type: String },
{ name: "url", alias: "u", type: String },
{ name: "write", alias: "w", type: Boolean },
{ name: "out", alias: "o", type: String },
{ name: "dir", alias: "d", type: String },
{ name: "replace", alias: "r", type: Boolean },
];
const options = commandLineArgs(optionDefinitions)
console.log("GraphQL CRUD Generator\n")
console.log("Usage: npm run generate -- -t <table> -u <graphql_url> [-w:writefile] [-r:replace] -o <output_file> -d <base_dir>")
console.log("Minimal Usage: npm run generate -- -t users")
console.log("Example: npm run generate -- -t users -u http://localhost:5678 -wr -o Users.graphql\n")
if(!options.table) {
console.log("Incorrect command line args\n")
process.exit(0)
}
const tableName = options.table;
const gqlTableName = changeCase.capitalCase(tableName, {delimiter:""});
const gqlTypeName = changeCase.camelCase(tableName, {delimiter:""});
const outFile = options.out || (options.dir || "./") + gqlTableName + ".graphql";
const url = options.url || "http://localhost:5678/graphql";
console.log(
chalk.green("Creating .graphql file for table: ") + tableName + "\n"
);
let schema;
const getType = (type) => {
return schema.types.find((x) => x.name === type);
};
const cleanupGraphqlString = (gqlString) => {
return gqlString.replace(/,([^,]*)$/, "$1").trim()
}
const getPayload = (objectType, payload = "") => {
objectType.fields.forEach((field) => {
if (field.name !== clientMutationId) {
const type = field.type.ofType || field.type;
if (type.kind === GqlKinds.SCALAR || type.kind === GqlKinds.ENUM) {
payload += `${field.name},`;
}
}
});
return cleanupGraphqlString(payload);
};
const getScalarArgs = (inputType, argsObject, inputString = "", ignorePrimaryKey = false) => {
inputType.inputFields.forEach((field) => {
if (field.name !== clientMutationId && !(ignorePrimaryKey && field.name === primaryKey)) {
const type = field.type.ofType || field.type;
if (type.kind === GqlKinds.SCALAR || type.kind === GqlKinds.ENUM) {
inputString += `${field.name}:$${field.name}, `;
argsObject["$" + field.name] = `${type.name}${
(field.type.kind === GqlKinds.NON_NULL) ? "!" : ""
}`;
} else if (type.kind === GqlKinds.INPUT_OBJECT) {
const subType = getType(type.name);
inputString += `${field.name}:{${getScalarArgs(
subType,
argsObject,
inputString,
ignorePrimaryKey
)}}, `;
}
}
});
return cleanupGraphqlString(inputString);
};
const getMutationArgs = (mutation, argsArray, ignorePrimaryKey = false) => {
const input = mutation.args[0];
const inputType = getType(input.type.ofType.name);
return getScalarArgs(inputType, argsArray, "", ignorePrimaryKey);
};
const generateMutationString = (mutationName, ignorePrimaryKey = false) => {
const mutations = schema.types.find((x) => x.name == mutationTypeName);
const mutation = mutations.fields.find((x) => x.name === mutationName);
if (mutation) {
console.log("Generating mutation: " + mutationName);
let argsObject = {};
const inputString = getMutationArgs(mutation, argsObject, ignorePrimaryKey);
const formattedArgs = JSON.stringify(argsObject)
.replace("{", "")
.replace("}", "")
.replace(/\"/g, "");
const payloadType = getType(gqlTableName);
const payload = getPayload(payloadType);
let mutationString = `
mutation ${mutationName}(${formattedArgs}) {
${mutationName}(
input: {${inputString}}
) {
${gqlTypeName} {
${payload}
}
}
}
`;
return prettier.format(mutationString, { semi: false, parser: "graphql" });
} else {
console.log(chalk.yellow("Could not find " + mutationName));
}
};
const generateMutations = () => {
const createMutation = generateMutationString("create" + gqlTableName, true);
const updateMutation = generateMutationString("update" + gqlTableName);
const deleteMutation = generateMutationString("delete" + gqlTableName);
console.log(chalk.green("\nGeneration finished, results below:\n"));
if (options.replace && options.write) {
if (fs.existsSync(outFile)) {
fs.unlinkSync(outFile);
}
}
if (createMutation) {
writeOutFile(createMutation);
}
if (updateMutation) {
writeOutFile(updateMutation);
}
if (deleteMutation) {
writeOutFile(deleteMutation);
}
};
const writeOutFile = (data) => {
console.log(data);
if (options.write) {
fs.appendFile(outFile, data + "\n", function (err) {
if (err) throw err;
});
}
};
const fetcher = (params) => {
return fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(params),
})
.then(function (response) {
return response.text();
})
.then(function (responseBody) {
try {
return JSON.parse(responseBody);
} catch (e) {
return responseBody;
}
});
};
const init = () => {
console.log(chalk.magenta("Reading schema at: " + url + "\n"));
fetcher({ query: getIntrospectionQuery() })
.then((result) => {
schema = result.data.__schema;
generateMutations();
})
.catch((err) => {
console.log(
chalk.red(
`Could not post introspection query to ${url}, error below: \n`
)
);
console.error(err);
});
};
init();