1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const change_case = require("change-case");
|
4 | const handlebars = require("handlebars");
|
5 | const TEMPLATE = `/**
|
6 | * Auto generated, do not modify!
|
7 | */
|
8 | /* eslint-disable */
|
9 | import * as Knex from "knex";
|
10 | {{#each imports}}{{{this}}}
|
11 | {{/each}}
|
12 |
|
13 | export default class Inserter {
|
14 | constructor(private knex: Knex) {
|
15 |
|
16 | }
|
17 |
|
18 | async replaceInto<T>(tableName:string, arr:T[]|T):Promise<void> {
|
19 | let qry= this.knex(tableName).insert(arr as any).toString();
|
20 | await this.knex.raw(qry.replace("insert", "replace"));
|
21 | }
|
22 |
|
23 | async insertIgnore<T>(tableName:string, arr:T[]|T):Promise<void> {
|
24 | let qry= this.knex(tableName).insert(arr as any).toString();
|
25 | await this.knex.raw(qry.replace("insert", "insert ignore"));
|
26 | }
|
27 |
|
28 | async insert<T>(tableName: string, data: T | T[]): Promise<number[]> {
|
29 | return await this.knex(tableName).insert(data);
|
30 | }
|
31 |
|
32 | async batchInsert<T>(tableName: string, arr: T[]) {
|
33 | let chunkSize = 1000;
|
34 | await this.knex.batchInsert(tableName, arr, chunkSize);
|
35 | }
|
36 |
|
37 | {{#each inserters}}{{{this}}}{{/each}}
|
38 | {{#each batchInserters}}{{{this}}}{{/each}}
|
39 | }`;
|
40 | const INSERT_TEMPLATE = `
|
41 | async insert{{fnName}}(item: {{prefixedClassName}} | {{prefixedClassName}}[]): Promise<number[]> {
|
42 | return await this.insert("{{tableName}}", item);
|
43 | }
|
44 | `;
|
45 | const BATCH_INSERT_TEMPLATE = `
|
46 | async batchInsert{{fnPlural}}(item: {{prefixedClassName}}[]) {
|
47 | return await this.batchInsert("{{tableName}}", item);
|
48 | }
|
49 | `;
|
50 | class InserterBuilder {
|
51 | constructor() {
|
52 | this.compiledTemplate = handlebars.compile(TEMPLATE);
|
53 | this.compiledInsertTemplate = handlebars.compile(INSERT_TEMPLATE);
|
54 | this.compiledBatchInsertTemplate = handlebars.compile(BATCH_INSERT_TEMPLATE);
|
55 | }
|
56 | render(tables, relativePath = "./") {
|
57 | tables = JSON.parse(JSON.stringify(tables));
|
58 | tables.forEach(t => {
|
59 | t.fnName = change_case.upperCaseFirst(t.fnName);
|
60 | t.fnPlural = change_case.upperCaseFirst(t.fnPlural);
|
61 | });
|
62 | const input = {
|
63 | batchInserters: tables.map(t => this.compiledBatchInsertTemplate(t)),
|
64 | imports: tables.map(t => this.renderImportRow(t, relativePath)),
|
65 | inserters: tables.map(t => this.compiledInsertTemplate(t))
|
66 | };
|
67 | return this.compiledTemplate(input);
|
68 | }
|
69 | renderImportRow(table, relativePath) {
|
70 | table = JSON.parse(JSON.stringify(table));
|
71 | table.filename = table.filename.replace(".ts", "");
|
72 | return `import {${table.prefixedClassName}} from "${relativePath}${table.filename}"`;
|
73 | }
|
74 | }
|
75 | exports.InserterBuilder = InserterBuilder;
|
76 |
|
\ | No newline at end of file |