-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimmutable_genfile.ts
More file actions
executable file
·338 lines (282 loc) · 9.61 KB
/
immutable_genfile.ts
File metadata and controls
executable file
·338 lines (282 loc) · 9.61 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
** Immutable GenFile **
Generate a genfile for the immutable generator
- requires a entity name as an argument
*/
import fs from "fs";
import { join } from "./utils/path";
import { getNamesFromSingularSnakeCase as getNames } from "./utils/string";
import { log } from "./utils/logger";
const [, , genName] = process.argv;
const file = join(process.cwd(), `.genfile_${genName}.ts`);
if (!genName) {
console.error("Please provide a name as an argument.");
process.exit(1);
}
const main = () => (fs.existsSync(file) ? update_genfile() : new_genfile());
const new_genfile = () => {
const {
singleUpperCamel,
singleLowerCamel,
pluralUpperCamel,
pluralLowerCamel,
} = getNames(genName) || {};
const tsContent = `
/*
*****************************
*** APPLICATION TYPE DECLARATIONS ***
Specify properties for ${singleLowerCamel} types.
Global will be used when other types are not specified. If all types are specified, Global will be ignored.
If genfile is run again with the same name argument, global will be propagated to all other types which can then be customized.
*****************************
*/
interface ImmutableGlobal
extends GenType<{
// * ${singleUpperCamel} *
example1: integer;
example2: string;
example3: float;
}> {}
interface AppState
extends GenType<{
${singleLowerCamel}: ${singleUpperCamel} | null;
${pluralLowerCamel}: ${singleUpperCamel}[];
}> {}
interface InitialAppState extends AppState {
${singleLowerCamel}: null;
${pluralLowerCamel}: [];
}
interface Schema extends GenType<{
// Schema here or use Global
}> {}
interface DatabaseTable extends GenType<{
// DatabaseTable here or use Global
}> {}
interface TsType extends GenType<{
// TsType here or use Global
}> {}
/*
****************************
*** GENERATOR ***
Comment out unwanted functionality or add new functionality for generation.
****************************
*/
const Immutable: ImmutableGenerator = {
name: "${genName}",
generate: {
// BACK END
http_controller: {
name: "${singleUpperCamel}Controller",
routes: [
"routed_index(conn, entity_queries, page_queries) when entity_queries == %{}",
"routed_index(conn, entity_queries, page_queries) when entity_queries != %{}",
"create(conn, ${genName}_list) when is_list(${genName}_list)",
"create(conn, ${genName}_params)",
"show(conn, ${genName}_list) when is_list(${genName}_list)",
'show(conn, %{"id" => id})',
"update(conn, ${genName}_list) when is_list(${genName}_list)",
"update(conn, ${genName}_params) when is_map(${genName}_params)",
"delete(conn, ${genName}_list) when is_list(${genName}_list)",
'delete(conn, %{"id" => id})',
// "custom_route(conn, %{destructured: params})"
],
},
channel_controller: "${genName}_channel",
context: {
name: "${singleUpperCamel}Context",
apiFunctions: [
"create_${genName}(attrs) when is_list(attrs)",
"create_${genName}(${genName}_params) when is_map(${genName}_params)",
"delete_${genName}(${pluralLowerCamel}) when is_list(${pluralLowerCamel})",
"delete_${genName}(${genName}_params) when is_map(${genName}_params)",
"delete_${genName}(id) when is_binary(id)",
"get_${genName}!(${pluralLowerCamel}) when is_list(${pluralLowerCamel})",
"get_${genName}!(${genName}_params) when is_map(${genName}_params)",
"get_${genName}!(id) when is_binary(id)",
"list_${pluralLowerCamel}(page_query \\ %{})",
"list_${pluralLowerCamel}_by(entity_queries, page_queries \\ %{})",
"update_${genName}(${pluralLowerCamel}) when is_list(${pluralLowerCamel})",
"update_${genName}(attrs) when is_map(attrs)",
// "custom_api_function(\${key: _value}) when is_binary('guard_clause')",
],
},
schema: "${singleUpperCamel}",
databaseTable: "${pluralLowerCamel}",
// FRONT END
requests: {
requestFunctions: [
"request${singleUpperCamel} = (${pluralLowerCamel}: ${singleUpperCamel}[], dispatch: Dispatch)",
"create${singleUpperCamel} = (${pluralLowerCamel}: ${singleUpperCamel}[], dispatch: Dispatch)",
"update${singleUpperCamel} = (${singleLowerCamel}: ${singleUpperCamel}[], dispatch: Dispatch)",
"delete${singleUpperCamel} = (${singleLowerCamel}: ${singleUpperCamel}[], dispatch: Dispatch)",
// "customRequest = (%{key: _value}, dispatch: Dispatch)",
],
},
stateSlice: {
name: "${singleLowerCamel}Slice",
reducers: [
"set${singleUpperCamel}(state: ${singleUpperCamel}StoreState, action: PayloadAction<${singleUpperCamel}>",
"set${pluralUpperCamel}(state: ${singleUpperCamel}StoreState, action: PayloadAction<${singleUpperCamel}[]>",
// "customReducer(state, action: PayloadAction<${singleUpperCamel}>)",
],
selectors: [
"select${singleUpperCamel} = (state: GenericAppState)",
"select${pluralUpperCamel} = (state: GenericAppState)",
// "customSelector = (state: GenericAppState)",
],
},
appstate: "${singleUpperCamel}StoreState",
tstype: "${singleUpperCamel}",
factory: true,
demoComponents: true,
test: true,
},
};
/*
****************************
*** PRIMITIVES ***
View and adjust primitive type associations between Elixir and Typescript
type ex_type = ts_type & { __brand: 'ex_type' };
****************************
*/
type integer = number & { __brand: "integer" };
type float = number & { __brand: "float" };
type decimal = number & { __brand: "decimal" };
// type string = string & { __brand: 'string' };
// type boolean = boolean & { __brand: 'boolean' };
type date = string & { __brand: "date" };
type time = string & { __brand: "time" };
type naive_datetime = string & { __brand: "naive_datetime" };
type utc_datetime = string & { __brand: "utc_datetime" };
type binary = string & { __brand: "binary" };
type array = any[] & { __brand: "array" };
type map = object & { __brand: "map" };
type json = object & { __brand: "json" };
type id = string & { __brand: "id" };
type uuid = string & { __brand: "uuid" };
type binary_id = string & { __brand: "binary_id" };
/*
****************************
*** INTERNAL USE ***
The following types are unused other than to provide in-editor type checking for the fields above
****************************
*/
interface AllowedTypes {
[key: string]:
| integer
| float
| decimal
| string
| boolean
| date
| time
| naive_datetime
| utc_datetime
| binary
| array
| map
| json
| id
| uuid
| binary_id
// unique types for appstate only
| ${singleUpperCamel}
| ${singleUpperCamel}[]
| null;
}
interface ${singleUpperCamel} {}
type GenType<T extends AllowedTypes> = T;
interface ImmutableGenerator {
name: string;
generate: {
requests?: ImmutableRequests;
stateSlice?: ImmutableStateSlice;
http_controller?: ImmutableController;
channel_controller?: string;
context?: ImmutableContext;
databaseTable?: string;
schema?: string;
tstype?: string;
appstate?: string;
factory?: boolean;
demoComponents?: boolean;
test?: boolean;
};
}
interface ImmutableController {
name: string;
routes: string[];
}
interface ImmutableContext {
name: string;
apiFunctions: string[];
}
interface ImmutableStateSlice {
name: string;
reducers?: string[];
selectors?: string[];
}
interface ImmutableRequests {
requestFunctions: string[];
}
export { Immutable };
export type {
ImmutableGenerator,
ImmutableGlobal,
AppState,
InitialAppState,
Schema,
DatabaseTable,
TsType,
ImmutableContext,
ImmutableController,
ImmutableRequests,
ImmutableStateSlice,
};
`;
fs.writeFileSync(`.genfile_${genName}.ts`, tsContent, "utf8");
log({ level: 1, color: "GREEN" }, `\nCreated .genfile_${genName}.ts`);
log({ level: 1, color: "BLUE" }, ` in ${file}\n\n`);
};
const update_genfile = () => {
const fileContent = fs.readFileSync(file, "utf8");
let updatedContent = fileContent;
const interfaces = fileContent.match(
/interface \w+.*?extends GenType<.*?> \{\}/gs
);
const parsed = interfaces?.map((str: string) => parse_interface(str));
const [_, global_def] =
parsed?.find(([name, _]) => name === "ImmutableGlobal") || [];
const updated_interfaces = parsed?.map(
([_name, definition, _fullstr], i: number) => {
if (definition.length === 0 && global_def) {
let res = "";
interfaces?.[i].replace(
/interface\s(\w+).*?extends\sGenType<\{(.*?)\}?> \{\}/gs,
(name, _attr, _str) => {
res = `interface ${name} extends GenType<{${global_def}}> {}`;
return res;
}
);
return res;
} else return interfaces?.[i];
}
);
updated_interfaces?.forEach((interf, index) => {
if (interf)
updatedContent = updatedContent.replace(
interfaces?.[index] || "",
interf
);
});
fs.writeFileSync(`.genfile_${genName}.ts`, updatedContent, "utf8");
log({ level: 1, color: "GREEN" }, `\nUpdated .genfile_${genName}.ts`);
log({ level: 1, color: "BLUE" }, ` in ${file}\n\n`);
};
main();
// Utils
const parse_interface = (str: string): [string, string, string] => {
const name = str.match(/interface\s(\w+)/)?.[1] || "";
const attr = str.match(/\w+\:\s\w+/gs)?.join("\n") || "";
return [name, attr, str];
};