UNPKG

typescript-mysql-model

Version:

{ "version": "1.2.46", "name": "typescript-mysql-model", "description": "", "main": "index.js", "types": "index.d.ts", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url":

76 lines (69 loc) 2.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const change_case = require("change-case"); const handlebars = require("handlebars"); const TEMPLATE = `/** * Autogenerated, do not modify */ /* tslint:disable */ import * as Knex from "knex"; {{#each imports}}{{{this}}} {{/each}} export default class Inserter { constructor(private knex: Knex) { } async replaceInto<T>(tableName:string, arr:T[]|T):Promise<void> { let qry= this.knex(tableName).insert(arr as any).toString(); await this.knex.raw(qry.replace("insert", "replace")); } async insertIgnore<T>(tableName:string, arr:T[]|T):Promise<void> { let qry= this.knex(tableName).insert(arr as any).toString(); await this.knex.raw(qry.replace("insert", "insert ignore")); } async insert<T>(tableName: string, data: T | T[]): Promise<number[]> { return await this.knex(tableName).insert(data); } async batchInsert<T>(tableName: string, arr: T[]) { let chunkSize = 1000; await this.knex.batchInsert(tableName, arr, chunkSize); } {{#each inserters}}{{{this}}}{{/each}} {{#each batchInserters}}{{{this}}}{{/each}} }`; const INSERT_TEMPLATE = ` async insert{{fnName}}(item: {{prefixedClassName}} | {{prefixedClassName}}[]): Promise<number[]> { return await this.insert("{{tableName}}", item); } `; const BATCH_INSERT_TEMPLATE = ` async batchInsert{{fnPlural}}(item: {{prefixedClassName}}[]) { return await this.batchInsert("{{tableName}}", item); } `; class InserterBuilder { constructor() { this.compiledTemplate = handlebars.compile(TEMPLATE); this.compiledInsertTemplate = handlebars.compile(INSERT_TEMPLATE); this.compiledBatchInsertTemplate = handlebars.compile(BATCH_INSERT_TEMPLATE); } render(tables, relativePath = "./") { tables = JSON.parse(JSON.stringify(tables)); tables.forEach(t => { t.fnName = change_case.upperCaseFirst(t.fnName); t.fnPlural = change_case.upperCaseFirst(t.fnPlural); }); const input = { batchInserters: tables.map(t => this.compiledBatchInsertTemplate(t)), imports: tables.map(t => this.renderImportRow(t, relativePath)), inserters: tables.map(t => this.compiledInsertTemplate(t)) }; return this.compiledTemplate(input); } renderImportRow(table, relativePath) { table = JSON.parse(JSON.stringify(table)); table.filename = table.filename.replace(".ts", ""); return `import {${table.prefixedClassName}} from "${relativePath}${table.filename}"`; } } exports.InserterBuilder = InserterBuilder; //# sourceMappingURL=inserter-builder.js.map