sequelize-ts-boilerplate
Version:
A REST API scaffolding tool designed to scale and easily generate CRUD endpoints based on database schema design
55 lines (44 loc) • 2.44 kB
text/typescript
import { Table } from "../classes/Table";
import { IConfig } from "../../interfaces/config";
import utils from "../../utils/general-utils";
export function get(table: Table, config: IConfig) {
const pkLower = config.ORM_GENERATE.pkIdentifier;
const pkUpper = utils.capitalizeFirstLetter(pkLower);
const upperCaseTableName = utils.capitalizeFirstLetter(table.tableName);
const lowerCaseTableName = utils.lowerCaseFirstLetter(table.tableName);
const pluralizedUpperCaseTableName = utils.capitalizeFirstLetter(utils.pluralize(upperCaseTableName));
const opts = `raw: true`;
return (`
public findAll${pluralizedUpperCaseTableName} = async () => {
return await ${upperCaseTableName}.findAll({${opts}});
}
public findAll${pluralizedUpperCaseTableName}By${pkUpper} = async (${pkLower}: number) => {
return await ${upperCaseTableName}.findAll({where: {${pkLower}}, ${opts}});
}
public findOne${upperCaseTableName}By${pkUpper} = async (${pkLower}: number) => {
return await ${upperCaseTableName}.findOne({where: {${pkLower}}, ${opts}});
}
public update${upperCaseTableName} = async (${lowerCaseTableName}) => {
return await ${upperCaseTableName}.update({...${lowerCaseTableName}}, {where: {${pkLower}: ${lowerCaseTableName}['${pkLower}']}});
}
public save${upperCaseTableName} = async (${lowerCaseTableName}) => {
return await new ${upperCaseTableName}({...${lowerCaseTableName}}).save();
}
public batchSave${pluralizedUpperCaseTableName} = async (${pluralizedUpperCaseTableName.toLowerCase()}: ${upperCaseTableName}[]) => {
return await ${upperCaseTableName}.bulkCreate(${pluralizedUpperCaseTableName.toLowerCase()}.map((x) => {
// do work here
return {
// customize obj props, if necessary
...x
};
}))
}
public delete${upperCaseTableName}By${pkUpper} = async (${pkLower}: number) => {
return await ${upperCaseTableName}.destroy({where: {${pkLower}}});
}
/************************** Methods not attached to 'Controller' below here ******************************/
public findAll${pluralizedUpperCaseTableName}ByColumns = async (columns: {[key:string]: any}) => {
return await ${upperCaseTableName}.findAll({where: {...columns}, ${opts}});
}
`)
}