From 473541b3f30baa7b93a91859c1c6e6a8e29f2043 Mon Sep 17 00:00:00 2001
From: YUAN21 <1650192445@qq.com>
Date: Fri, 20 Nov 2020 15:21:10 +0800
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E5=A2=9E=E5=8A=A0=E9=85=8D?=
=?UTF-8?q?=E7=BD=AE=E9=A1=B9=EF=BC=88type=3Dfreesun=EF=BC=89=E9=80=82?=
=?UTF-8?q?=E9=85=8D=E9=A3=9E=E5=B0=9A=E6=9E=B6=E6=9E=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 267 +++++++++++++-----------
package.json | 8 +-
src/generate/freesun.js | 92 ++++++++
src/generate/index.js | 3 +
src/generate/template/freesun/user.text | 72 +++++++
src/index.js | 19 +-
src/util/definition.js | 53 +++--
src/util/write.js | 2 +-
8 files changed, 366 insertions(+), 150 deletions(-)
create mode 100644 src/generate/freesun.js
create mode 100644 src/generate/template/freesun/user.text
diff --git a/README.md b/README.md
index 47162ac..af94930 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,6 @@
-# Sequelize-Automate
+# Sequelize-Automate-Freesun
+
+
[![NPM version][npm-image]][npm-url]
[![npm download][download-image]][download-url]
@@ -10,7 +12,6 @@
-
[npm-image]: https://img.shields.io/npm/v/sequelize-automate.svg?style=flat-square
@@ -26,6 +27,7 @@
[download-image]: https://img.shields.io/npm/dm/sequelize-automate.svg?style=flat-square
[download-url]: https://npmjs.org/package/sequelize-automate
+
Automatically generate models for [SequelizeJS](https://github.com/sequelize/sequelize). Support javascript, typescript, egg.js and midway.
@@ -34,8 +36,9 @@ Automatically generate models for [SequelizeJS](https://github.com/sequelize/seq
### global
```shell script
-$ npm install -g sequelize-automate
-```
+$ npm install -g sequelize-automate-freesun
+
+```
You'll also have to manually install the driver for your database of choice:
@@ -51,8 +54,9 @@ $ npm install -g tedious # Microsoft SQL Server
### in project
```shell script
-$ npm install sequelize-automate --save
-```
+$ npm install sequelize-automate-freesun --save
+
+```
You'll also have to manually install the driver for your database of choice:
@@ -65,7 +69,6 @@ $ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
```
-
## Usage
### Command Line
@@ -77,24 +80,35 @@ Options:
--version Show version number [boolean]
--help Show help [boolean]
--type, -t Which code style want to generate.
+
[choices: "js", "ts", "egg", "midway", "@ali/midway"]
+
--host, -h IP/Hostname for the database. [string] [default: "localhost"]
--database, -d Database name. [string] [default: "test"]
--user, -u Username for database. [string] [default: "root"]
--password, -p Password for database. [string] [default: "root"]
--port, -P Port number for database. e.g. MySQL/MariaDB: 3306, Postgres:
+
5432, MSSQL: 1433 [number]
- --dialect, -e The dialect/engine that you're using: mysql, sqlite, postgres,
+
+ --dialect, -e The dialect/engine that you're using: mysql, sqlite, postgres,
+
mssql
[choices: "mysql", "sqlite", "postgres", "mssql"] [default: "mysql"]
+
--output, -o What directory to place the models.
+
[string] [default: "models"]
+
--camel, -C Use camel case to name models [boolean] [default: false]
--config, -c Sequelize automate config file, see README.md [string]
--emptyDir, -r Remove all files in `dir` and `typesDir` directories before
+
generate models. [boolean] [default: false]
+
--match, -m Match tables using given RegExp. [string] [default: null]
-```
+
+```
#### Example
@@ -104,67 +118,67 @@ $ sequelize-automate -t js -h localhost -d test -u root -p root -P 3306 -e mysq
Produces a file/files such as ./models/user.js which looks like:
-```javascript
+``` javascript
const {
- DataTypes
+ DataTypes
} = require('sequelize');
module.exports = sequelize => {
- const attributes = {
- id: {
- type: DataTypes.INTEGER(11).UNSIGNED,
- allowNull: false,
- defaultValue: null,
- primaryKey: true,
- autoIncrement: true,
- comment: "primary ket",
- field: "id"
- },
- name: {
- type: DataTypes.STRING(100),
- allowNull: false,
- defaultValue: null,
- primaryKey: false,
- autoIncrement: false,
- comment: "user name",
- field: "name",
- unique: "uk_name"
- },
- email: {
- type: DataTypes.STRING(255),
- allowNull: false,
- defaultValue: null,
- primaryKey: false,
- autoIncrement: false,
- comment: "user email",
- field: "email"
- },
- createdAt: {
- type: DataTypes.DATE,
- allowNull: false,
- defaultValue: null,
- primaryKey: false,
- autoIncrement: false,
- comment: "created datetime",
- field: "created_at"
- },
- updatedAt: {
- type: DataTypes.DATE,
- allowNull: false,
- defaultValue: null,
- primaryKey: false,
- autoIncrement: false,
- comment: "updated datetime",
- field: "updated_at"
- }
- };
- const options = {
- tableName: "user",
- comment: "",
- indexes: []
- };
- const UserModel = sequelize.define("userModel", attributes, options);
- return UserModel;
+ const attributes = {
+ id: {
+ type: DataTypes.INTEGER(11).UNSIGNED,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: "primary ket",
+ field: "id"
+ },
+ name: {
+ type: DataTypes.STRING(100),
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: "user name",
+ field: "name",
+ unique: "uk_name"
+ },
+ email: {
+ type: DataTypes.STRING(255),
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: "user email",
+ field: "email"
+ },
+ createdAt: {
+ type: DataTypes.DATE,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: "created datetime",
+ field: "created_at"
+ },
+ updatedAt: {
+ type: DataTypes.DATE,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: "updated datetime",
+ field: "updated_at"
+ }
+ };
+ const options = {
+ tableName: "user",
+ comment: "",
+ indexes: []
+ };
+ const UserModel = sequelize.define("userModel", attributes, options);
+ return UserModel;
};
```
@@ -176,7 +190,8 @@ You can use `-c, --config` option to specify a configuration file.
```shell script
$ sequelize-automate -c "./sequelize-automate.config.json"
-```
+
+```
For now, you must create a file called `sequelize-automate.config.json` with the following content:
@@ -200,21 +215,21 @@ For now, you must create a file called `sequelize-automate.config.json` with the
Or a `.js` file: `sequelize-automate -c "./sequelize-automate.config.js"`
-```javascript
+``` javascript
module.exports = {
- dbOptions: {
- database: "test",
- username: "root",
- password: "root",
- dialect: "mysql",
- host: "localhost",
- port: 3306,
- logging: false
- },
- options: {
- type: "js",
- dir: "models"
- }
+ dbOptions: {
+ database: "test",
+ username: "root",
+ password: "root",
+ dialect: "mysql",
+ host: "localhost",
+ port: 3306,
+ logging: false
+ },
+ options: {
+ type: "js",
+ dir: "models"
+ }
}
```
@@ -222,9 +237,9 @@ module.exports = {
Also, you can use `sequelize-automate` in project.
-First add a configuration file `sequelize-automate.config.json` as above and add `automate` script to `package.json`:
+First add a configuration file `sequelize-automate.config.json` as above and add `automate` script to `package.json` :
-```json
+``` json
"script": {
"automate": "sequelize-automate -c sequelize-automate.config.json"
}
@@ -232,56 +247,58 @@ First add a configuration file `sequelize-automate.config.json` as above and add
Then you can use `npm run automate` to generate models.
-
## Programmatic API
-```javascript
+``` javascript
const Automate = require('sequelize-automate');
// Database options, is the same with sequelize constructor options.
const dbOptions = {
- database: 'test',
- username: 'root',
- password: 'root',
- dialect: 'mysql',
- host: '127.0.0.1',
- port: 3306,
- define: {
- underscored: false,
- freezeTableName: false,
- charset: 'utf8mb4',
- timezone: '+00:00',
- dialectOptions: {
- collate: 'utf8_general_ci',
+ database: 'test',
+ username: 'root',
+ password: 'root',
+ dialect: 'mysql',
+ host: '127.0.0.1',
+ port: 3306,
+ define: {
+ underscored: false,
+ freezeTableName: false,
+ charset: 'utf8mb4',
+ timezone: '+00:00',
+ dialectOptions: {
+ collate: 'utf8_general_ci',
+ },
+ timestamps: false,
},
- timestamps: false,
- },
};
// Automate options
const options = {
- type: 'js', // Which code style want to generate, supported: js/ts/egg/midway. Default is `js`.
- camelCase: false, // Model name camel case. Default is false.
- fileNameCamelCase: true, // Model file name camel case. Default is false.
- dir: 'models', // What directory to place the models. Default is `models`.
- typesDir: 'models', // What directory to place the models' definitions (for typescript), default is the same with dir.
- emptyDir: false, // Remove all files in `dir` and `typesDir` directories before generate models.
- tables: null, // Use these tables, Example: ['user'], default is null.
- skipTables: null, // Skip these tables. Example: ['user'], default is null.
- tsNoCheck: false, // Whether add @ts-nocheck to model files, default is false.
- match: null // RegExp to match table name
+ type: 'js', // Which code style want to generate, supported: js/ts/egg/midway. Default is `js` .
+ camelCase: false, // Model name camel case. Default is false.
+ fileNameCamelCase: true, // Model file name camel case. Default is false.
+ modalNameSuffix: true, // Model name 'Modal' suffix. Default is true.
+ dir: 'models', // What directory to place the models. Default is `models` .
+ typesDir: 'models', // What directory to place the models' definitions (for typescript), default is the same with dir.
+ emptyDir: false, // Remove all files in `dir` and `typesDir` directories before generate models.
+ tables: null, // Use these tables, Example: ['user'], default is null.
+ skipTables: null, // Skip these tables. Example: ['user'], default is null.
+ tsNoCheck: false, // Whether add @ts-nocheck to model files, default is false.
+ match: null, // RegExp to match table name
+ ignorePrefix: null, // Ignore the prefix of table name, Example: ['t_']. Default is null
+ attrLength: true, // Whether to generate attribute length(design for freesun,but use for any type)
}
const automate = new Automate(dbOptions, options);
(async function main() {
- // // get table definitions
- // const definitions = await automate.getDefinitions();
- // console.log(definitions);
+ // // get table definitions
+ // const definitions = await automate.getDefinitions();
+ // console.log(definitions);
- // or generate codes
- const code = await automate.run();
- console.log(code);
+ // or generate codes
+ const code = await automate.run();
+ console.log(code);
})()
```
@@ -289,14 +306,20 @@ Database options `dbOptions` is the same with sequelize constructor options, you
### Methods
-- `automate.getDefinitions()`: Get all model definitions. `sequelize-automate` will use these definitions to generate different codes.
-- `automate.run()`: Generate model codes.
-
+* `automate.getDefinitions()` : Get all model definitions. `sequelize-automate` will use these definitions to generate different codes.
+* `automate.run()` : Generate model codes.
## Type
You can generate different (node.js framework's) codes use `type` option.
+### Freesun
+
+```shell script
+$ sequelize-automate -t freesun
+
+```
+
### JavaScript
```shell script
@@ -309,7 +332,8 @@ $ sequelize-automate -t js
```shell script
$ sequelize-automate -t ts
-```
+
+```
[example](https://github.com/nodejh/sequelize-automate/tree/master/src/generate/template/typescript)
@@ -321,7 +345,6 @@ $ sequelize-automate -t egg
[example](https://github.com/nodejh/sequelize-automate/tree/master/src/generate/template/egg)
-
### Midway.js
```shell script
@@ -330,7 +353,7 @@ $ sequelize-automate -t midway
[example](https://github.com/nodejh/sequelize-automate/tree/master/src/generate/template/midway)
-If you want to generate codes for other frameworks, please let me know.
+~~If you want to generate codes for other frameworks, please let me know.~~
## LICENSE
diff --git a/package.json b/package.json
index 48fd435..3add4d1 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,5 @@
{
- "name": "sequelize-automate",
+ "name": "sequelize-automate-freesun",
"version": "1.2.2",
"description": "Automatically generate bare sequelize models from your database.",
"main": "index",
@@ -15,10 +15,10 @@
},
"repository": {
"type": "git",
- "url": "https://github.com/nodejh/sequelize-automate.git"
+ "url": "https://github.com/xiapazhi/sequelize-automate.git"
},
"bugs": {
- "url": "https://github.com/nodejh/sequelize-automate/issues"
+ "url": "https://github.com/xiapazhi/sequelize-automate/issues"
},
"nyc": {
"exclude": [
@@ -33,7 +33,7 @@
"engines": {
"node": ">=0.10"
},
- "author": "nodejh ",
+ "author": "xiapazhi ",
"license": "MIT",
"dependencies": {
"@babel/generator": "^7.7.4",
diff --git a/src/generate/freesun.js b/src/generate/freesun.js
new file mode 100644
index 0000000..7041658
--- /dev/null
+++ b/src/generate/freesun.js
@@ -0,0 +1,92 @@
+const { parse } = require('@babel/parser');
+const { default: generate } = require('@babel/generator');
+const t = require('@babel/types');
+const { default: traverse } = require('@babel/traverse');
+const fs = require('fs');
+const { join } = require('path');
+const { bigCamelCase } = require('../util/wordCase');
+const {
+ generateOptions,
+ processAttributesProperties,
+ processOptionsProperties,
+} = require('./common/index');
+
+
+/**
+ * Generate codes
+ * @param {object} definition
+ * @param {object} options
+ */
+function generateCode(definition, options) {
+ const file = './template/freesun/user.text'
+ const source = fs
+ .readFileSync(join(__dirname, file))
+ .toString();
+
+ const ast = parse(source, {
+ strictMode: true,
+ });
+
+ traverse(ast, {
+ VariableDeclarator: (path) => {
+ const { node } = path;
+
+ if (t.isIdentifier(node.id, { name: 'UserModel' })) {
+ node.id = t.identifier(bigCamelCase(definition.modelName));
+ }
+ },
+
+ CallExpression: (path) => {
+ const { node } = path;
+ if (
+ t.isMemberExpression(node.callee)
+ && t.isIdentifier(node.callee.property, { name: 'define' })
+ ) {
+ node.arguments[0] = t.stringLiteral(definition.modelName);
+ node.arguments[1] = t.objectExpression(processAttributesProperties(definition.attributes));
+ node.arguments[2] = t.objectExpression(processOptionsProperties(
+ node.arguments[2].properties,
+ definition,
+ ));
+ }
+ },
+
+ ExpressionStatement: (path) => {
+ const { node } = path;
+ if (t.isIdentifier(node.expression.left.property, { name: 'UserModel' })) {
+ node.expression.left.property.name = bigCamelCase(definition.modelName);
+ }
+ if (t.isIdentifier(node.expression.right, { name: 'UserModel' })) {
+ node.expression.right.name = bigCamelCase(definition.modelName);
+ }
+ },
+
+ ReturnStatement: (path) => {
+ const { node } = path;
+ if (t.isIdentifier(node.argument, { name: 'UserModel' })) {
+ node.argument = t.identifier(bigCamelCase(definition.modelName));
+ }
+ },
+ });
+
+
+ const { code } = generate(ast, generateOptions);
+ return code;
+}
+
+function process(definitions, options) {
+ const modelCodes = definitions.map((definition) => {
+ const { modelFileName } = definition;
+ const fileType = 'model';
+ const file = `${modelFileName}.js`;
+ const code = generateCode(definition, options);
+ return {
+ file,
+ code,
+ fileType,
+ };
+ });
+ return modelCodes;
+}
+
+module.exports = process;
diff --git a/src/generate/index.js b/src/generate/index.js
index ef8c2a8..ae74c5e 100644
--- a/src/generate/index.js
+++ b/src/generate/index.js
@@ -1,3 +1,4 @@
+const processFS = require('./freesun');
const processJS = require('./javascript');
const processTS = require('./typescript');
const processMidway = require('./midway');
@@ -11,6 +12,8 @@ const processMidway = require('./midway');
function generate(definition, options) {
const { type, tsNoCheck } = options;
switch (type) {
+ case 'freesun':
+ return processFS(definition, { isEgg: false });
case 'js':
return processJS(definition, { isEgg: false });
case 'ts':
diff --git a/src/generate/template/freesun/user.text b/src/generate/template/freesun/user.text
new file mode 100644
index 0000000..8c00e5a
--- /dev/null
+++ b/src/generate/template/freesun/user.text
@@ -0,0 +1,72 @@
+/* eslint-disable*/
+
+'use strict';
+
+module.exports = dc => {
+ const DataTypes = dc.ORM;
+ const sequelize = dc.orm;
+
+ const UserModel = sequelize.define('userModel',{
+ id: {
+ type: DataTypes.BIGINT,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: null,
+ field: 'id',
+ unique: 'uk_id',
+ },
+ name: {
+ type: DataTypes.STRING(32),
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: 'user name',
+ field: 'name',
+ },
+ email: {
+ type: DataTypes.STRING(32),
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: 'user email',
+ field: 'name',
+ },
+ createdAt: {
+ type: DataTypes.DATE,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: 'created time',
+ field: 'created_at',
+ },
+ updatedAt: {
+ type: DataTypes.DATE,
+ allowNull: false,
+ defaultValue: null,
+ primaryKey: false,
+ autoIncrement: false,
+ comment: 'update time',
+ field: 'updated_at',
+ },
+ },{
+ tableName: 'user',
+ comment: 'user table',
+ indexes: [{
+ name: 'uk_name_email',
+ unique: true,
+ fields: [
+ 'name',
+ 'email',
+ ],
+ }]
+ });
+
+ dc.models.UserModel = UserModel;
+
+ return UserModel;
+};
diff --git a/src/index.js b/src/index.js
index eb356e6..4052ffa 100644
--- a/src/index.js
+++ b/src/index.js
@@ -21,7 +21,9 @@ class Automate {
tables: null, // Use these tables, Example: ['user'], default is null.
skipTables: null, // Skip these tables. Example: ['user'], default is null.
tsNoCheck: false, // Whether add `@ts-nocheck` to model files, default is false.
- match: null // Regex to match table name
+ match: null, // Regex to match table name,
+ ignorePrefix: null, // Ignore the prefix of table name(for freesun), Example: ['t_']. Default is null
+ attrLength: true,// Whether to generate attribute length(design for freesun,but use for any type)
};
// https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor
@@ -31,7 +33,7 @@ class Automate {
// default `options.typesDir` is the same with `options.dir`
this.options.typesDir = this.options.typesDir || this.options.dir;
- const supportTypes = ['js', 'ts', 'egg', 'midway', '@ali/midway'];
+ const supportTypes = ['freesun', 'js', 'ts', 'egg', 'midway', '@ali/midway'];
assert(supportTypes.includes(this.options.type), 'type not support');
assert(_.isBoolean(this.options.camelCase), 'Invalid params camelCase');
assert(_.isBoolean(this.options.fileNameCamelCase), 'Invalid params fileNameCamelCase');
@@ -40,8 +42,10 @@ class Automate {
assert(_.isString(this.options.typesDir), 'Invalid params typesDir');
assert(_.isBoolean(this.options.emptyDir), 'Invalid params cleanDir');
assert(_.isNull(this.options.tables) || _.isArray(this.options.tables), 'Invalid params table');
- assert(_.isNull(this.options.skipTables) || _.isArray(this.options.skipTables), 'invalid params table');
+ assert(_.isNull(this.options.skipTables) || _.isArray(this.options.skipTables), 'invalid params skipTables');
assert(_.isBoolean(this.options.tsNoCheck), 'Invalid params tsNoCheck');
+ assert(_.isNull(this.options.ignorePrefix) || _.isArray(this.options.ignorePrefix), 'invalid params ignorePrefix');
+ assert(_.isBoolean(this.options.attrLength), 'Invalid params attrLength');
this.sequelize = new Sequelize(this.dbOptions);
this.queryInterface = this.sequelize.getQueryInterface();
@@ -89,6 +93,7 @@ class Automate {
});
debug('tableNames: ', tableNames);
+
const tableStructures = await Promise.all(tableNames.map(
(tableName) => this.queryInterface.describeTable(tableName),
));
@@ -122,6 +127,8 @@ class Automate {
camelCase,
fileNameCamelCase,
modalNameSuffix,
+ ignorePrefix,
+ attrLength,
} = this.options;
const allTables = await this.getTables({
tables,
@@ -132,6 +139,8 @@ class Automate {
fileNameCamelCase,
modalNameSuffix,
dialect: this.dbOptions.dialect,
+ ignorePrefix,
+ attrLength,
});
debug('get model definitions');
return definitions;
@@ -149,12 +158,16 @@ class Automate {
dir,
typesDir,
emptyDir,
+ ignorePrefix,
+ attrLength,
} = this.options;
const definitions = await this.getDefinitions({
tables,
skipTables,
camelCase,
fileNameCamelCase,
+ ignorePrefix,
+ attrLength,
});
const codes = generate(definitions, {
diff --git a/src/util/definition.js b/src/util/definition.js
index 4e0c1d8..0b4bba7 100644
--- a/src/util/definition.js
+++ b/src/util/definition.js
@@ -2,15 +2,24 @@ const _ = require('lodash');
const regexpPostgresAutoIncrementValue = /nextval\(.*seq::regclass\)/;
-function getFieldName(fieldName, camelCase) {
- return camelCase ? _.camelCase(fieldName) : fieldName;
+function getFieldName(fieldName, { camelCase, ignorePrefix }) {
+ let nameString = fieldName;
+ if (_.isArray(ignorePrefix)) {
+ for (let p of ignorePrefix) {
+ if (nameString.indexOf(p) == 0) {
+ nameString = nameString.slice(p.length);
+ break;
+ }
+ }
+ }
+ return camelCase ? _.camelCase(nameString) : nameString;
}
-function getModelName(tableName, camelCase, modalNameSuffix) {
+function getModelName(tableName, { camelCase, modalNameSuffix, ignorePrefix }) {
const modelString = modalNameSuffix ?
camelCase ? 'Model' : '_model'
: '';
- return `${getFieldName(tableName, camelCase)}${modelString}`;
+ return `${getFieldName(tableName, { camelCase, ignorePrefix })}${modelString}`;
}
@@ -89,9 +98,11 @@ function getAutoIncrement(field, dialect) {
/**
* Get data type
* @param {object} field table field
+ * @param {object} options { attrLength, }
* @return {string}
*/
-function getDataType(field) {
+function getDataType(field, option) {
+ const { attrLength } = option || {};
if (field.type.indexOf('ENUM') === 0) {
return `DataTypes.${field.type}`;
}
@@ -106,7 +117,9 @@ function getDataType(field) {
const length = attr.match(/\(\d+\)/);
// TODO: remove width for integer?
- const typeLength = !_.isNull(length) ? length : '';
+ const typeLength = attrLength ?
+ !_.isNull(length) ? length : ''
+ : '';
if (attr.match(/^(smallint|mediumint|tinyint|int)/)) {
let type = `DataTypes.INTEGER${typeLength}`;
const unsigned = attr.match(/unsigned/i);
@@ -135,7 +148,7 @@ function getDataType(field) {
return type;
}
- if (attr.match(/^varchar/)) {
+ if (attr.match(/^varchar/) || attr.match(/^character varying/)) {
return `DataTypes.STRING${typeLength}`;
}
@@ -197,7 +210,7 @@ function getDataType(field) {
/**
* Process a table
- * @param {object} params { structures, allIndexes, foreignKeys, options: { camelCase, dialect, modalNameSuffix } }
+ * @param {object} params { structures, allIndexes, foreignKeys, options: { camelCase, dialect, modalNameSuffix, attrLength } }
* @return {object} { attributes: { filed: { attribute } }, indexes: [{ name, type, fields }] }
*/
function processTable({
@@ -206,13 +219,13 @@ function processTable({
foreignKeys,
options,
}) {
- const { camelCase, dialect, modalNameSuffix } = options;
+ const { camelCase, dialect, modalNameSuffix, attrLength } = options;
const attributes = {};
_.forEach(structures, (structure, fieldName) => {
- const key = getFieldName(fieldName, camelCase);
+ const key = getFieldName(fieldName, { camelCase });
attributes[key] = _.cloneDeep(structure);
attributes[key].field = fieldName;
- attributes[key].type = getDataType(structure);
+ attributes[key].type = getDataType(structure, { attrLength });
attributes[key].defaultValue = getDefaultValue(structure, dialect);
attributes[key].autoIncrement = getAutoIncrement(structure, dialect);
});
@@ -222,11 +235,11 @@ function processTable({
const fields = index.fields.map((o) => o.attribute);
if (index.primary === true) {
_.forEach(fields, (fieldName) => {
- const field = getFieldName(fieldName, camelCase);
+ const field = getFieldName(fieldName, { camelCase });
attributes[field].primaryKey = true;
});
} else if (index.unique && fields.length === 1) {
- const field = getFieldName(fields[0], camelCase);
+ const field = getFieldName(fields[0], { camelCase });
attributes[field].unique = index.name;
} else {
indexes.push({
@@ -244,10 +257,10 @@ function processTable({
referencedTableName,
referencedColumnName,
} = foreignKey;
- const filed = getFieldName(columnName, camelCase);
+ const filed = getFieldName(columnName, { camelCase });
attributes[filed].references = {
key: referencedColumnName,
- model: getModelName(referencedTableName, camelCase, modalNameSuffix),
+ model: getModelName(referencedTableName, { camelCase, modalNameSuffix }),
};
});
@@ -257,21 +270,21 @@ function processTable({
/**
* Get model definitions
* @param {object} tables { structures, indexes, foreignKeys }
- * @param {object} options { camelCase, fileNameCamelCase, dialect, modalNameSuffix }
+ * @param {object} options { camelCase, fileNameCamelCase, dialect, modalNameSuffix, ignorePrefix, attrLength, }
* @return {object} [{ modelName, modelFileName, tableName, attributes, indexes }]
*/
function getModelDefinitions(tables, options) {
- const { camelCase, fileNameCamelCase, dialect, modalNameSuffix } = options || {};
+ const { camelCase, fileNameCamelCase, dialect, modalNameSuffix, ignorePrefix, attrLength } = options || {};
const definitions = _.map(tables, (table, tableName) => {
const { attributes, indexes } = processTable({
structures: table.structures,
allIndexes: table.indexes,
foreignKeys: table.foreignKeys,
- options: { camelCase, dialect, modalNameSuffix },
+ options: { camelCase, dialect, modalNameSuffix, attrLength },
});
- const modelName = getModelName(tableName, camelCase, modalNameSuffix);
- const modelFileName = getFieldName(tableName, fileNameCamelCase);
+ const modelName = getModelName(tableName, { camelCase, modalNameSuffix, ignorePrefix });
+ const modelFileName = getFieldName(tableName, { fileNameCamelCase, ignorePrefix });
return {
modelName,
modelFileName,
diff --git a/src/util/write.js b/src/util/write.js
index 4246b2e..d0bfce3 100644
--- a/src/util/write.js
+++ b/src/util/write.js
@@ -14,7 +14,7 @@ async function writeFile(code, dir, fileName) {
/**
* Write files
* @param {string} codes [{ file, code, fileType }]
- * @param {object} options { dir, typesDir }
+ * @param {object} options { dir, typesDir }
*/
async function write(codes, options) {
if (options.emptyDir) {