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":
96 lines (91 loc) • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Handlebars = require("handlebars");
const changeCase = require("change-case");
const template = `/**
* Autogenerated interface, DO NOT MODIFY
*/
/* tslint:disable */
import { {{imports}} } from "graphql";
{{{dateimport}}}
const {{name}}TypeFields = {
{{fields}}
};
const {{name}}InputType = new GraphQLInputObjectType({
fields: {{name}}TypeFields,
name: "{{name}}Input"
});
const {{name}}Type = new GraphQLObjectType({
fields: {{name}}TypeFields,
name: "{{name}}"
});
export { {{name}}Type, {{name}}InputType, {{name}}TypeFields };
`;
const GRAPH_QL_DATE_TIME = "GraphQLDateTime";
const GRAPH_QL_STRING = "GraphQLString";
class GraphQlBuilder {
constructor() {
this.compiledTemplate = Handlebars.compile(template);
this.mysqlTypes = {
blob: "string",
bigint: "int",
char: "string",
date: "datetime",
enum: "string",
datetime: "datetime",
decimal: "float",
double: "float",
float: "float",
int: "int",
longblob: "string",
longtext: "string",
mediumtext: "string",
set: "string",
smallint: "int",
text: "string",
timestamp: "datetime",
tinyint: "boolean",
varchar: "string"
};
}
renderTs(table, tableName) {
let types = Object.keys(table).map(colName => this.toGraphType(table[colName].type));
let dateimport = "";
if (types.some(t => t === GRAPH_QL_DATE_TIME)) {
dateimport = 'import { GraphQLDateTime } from "graphql-iso-date";';
}
types.push("GraphQLObjectType");
types.push("GraphQLInputObjectType");
types = types.filter(t => t !== GRAPH_QL_DATE_TIME);
types = types.filter((item, pos, self) => self.indexOf(item) === pos).sort();
const imports = types.join(", ");
const rows = Object.keys(table).map(colName => this.buildTypeRow(table[colName]));
const fields = rows.join(", \n \t\t");
const name = changeCase.pascalCase(tableName);
const t = this.compiledTemplate({ fields, name, imports, dateimport });
return t;
}
toGraphType(mysql) {
const s = this.mysqlTypes[mysql];
switch (s) {
case "string":
return GRAPH_QL_STRING;
case "float":
return "GraphQLFloat";
case "datetime":
return GRAPH_QL_DATE_TIME;
case "int":
return "GraphQLInt";
case "boolean":
return "GraphQLBoolean";
default:
throw "unknown type " + mysql;
}
}
buildTypeRow(col) {
const graphType = this.toGraphType(col.type);
return `${col.field}: { type: ${graphType} }`;
}
}
exports.default = GraphQlBuilder;
//# sourceMappingURL=graphql-builder.js.map