Skip to content

Commit 1db7369

Browse files
committed
add model-sequelize project
1 parent e8387ab commit 1db7369

File tree

13 files changed

+309
-0
lines changed

13 files changed

+309
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
"name": "Start",
6+
"type": "node",
7+
"request": "launch",
8+
"program": "${workspaceRoot}/start.js",
9+
"stopOnEntry": false,
10+
"args": [],
11+
"cwd": "${workspaceRoot}",
12+
"preLaunchTask": null,
13+
"runtimeExecutable": null,
14+
"runtimeArgs": [
15+
"--nolazy"
16+
],
17+
"env": {
18+
"NODE_ENV": "development"
19+
},
20+
"externalConsole": false,
21+
"sourceMaps": false,
22+
"outDir": null
23+
}
24+
]
25+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const model = require('./model');
2+
3+
let
4+
Pet = model.Pet,
5+
User = model.User;
6+
7+
(async () => {
8+
var user = await User.create({
9+
name: 'John',
10+
gender: false,
11+
email: 'john-' + Date.now() + '@garfield.pet',
12+
passwd: 'hahaha'
13+
});
14+
console.log('created: ' + JSON.stringify(user));
15+
var cat = await Pet.create({
16+
ownerId: user.id,
17+
name: 'Garfield',
18+
gender: false,
19+
birth: '2007-07-07',
20+
});
21+
console.log('created: ' + JSON.stringify(cat));
22+
var dog = await Pet.create({
23+
ownerId: user.id,
24+
name: 'Odie',
25+
gender: false,
26+
birth: '2008-08-08',
27+
});
28+
console.log('created: ' + JSON.stringify(dog));
29+
})();
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
var config = {
3+
dialect: 'mysql',
4+
database: 'nodejs',
5+
username: 'www',
6+
password: 'www',
7+
host: 'localhost',
8+
port: 3306
9+
};
10+
11+
module.exports = config;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
var config = {
3+
dialect: 'mysql',
4+
database: 'test',
5+
username: 'www',
6+
password: 'www',
7+
host: 'localhost',
8+
port: 3306
9+
};
10+
11+
module.exports = config;
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// config files:
2+
const defaultConfig = './config-default.js';
3+
const overrideConfig = './config-override.js';
4+
const testConfig = './config-test.js';
5+
6+
const fs = require('fs');
7+
8+
var config = null;
9+
10+
if (process.env.NODE_ENV === 'test') {
11+
console.log(`Load ${testConfig}...`);
12+
config = require(testConfig);
13+
} else {
14+
console.log(`Load ${defaultConfig}...`);
15+
config = require(defaultConfig);
16+
try {
17+
if (fs.statSync(overrideConfig).isFile()) {
18+
console.log(`Load ${overrideConfig}...`);
19+
config = Object.assign(config, require(overrideConfig));
20+
}
21+
} catch (err) {
22+
console.log(`Cannot load ${overrideConfig}.`);
23+
}
24+
}
25+
26+
module.exports = config;
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
const Sequelize = require('sequelize');
2+
3+
const uuid = require('node-uuid');
4+
5+
const config = require('./config');
6+
7+
console.log('init sequelize...');
8+
9+
function generateId() {
10+
return uuid.v4();
11+
}
12+
13+
var sequelize = new Sequelize(config.database, config.username, config.password, {
14+
host: config.host,
15+
dialect: config.dialect,
16+
pool: {
17+
max: 5,
18+
min: 0,
19+
idle: 10000
20+
}
21+
});
22+
23+
const ID_TYPE = Sequelize.STRING(50);
24+
25+
function defineModel(name, attributes) {
26+
var attrs = {};
27+
for (let key in attributes) {
28+
let value = attributes[key];
29+
if (typeof value === 'object' && value['type']) {
30+
value.allowNull = value.allowNull || false;
31+
attrs[key] = value;
32+
} else {
33+
attrs[key] = {
34+
type: value,
35+
allowNull: false
36+
};
37+
}
38+
}
39+
attrs.id = {
40+
type: ID_TYPE,
41+
primaryKey: true
42+
};
43+
attrs.createdAt = {
44+
type: Sequelize.BIGINT,
45+
allowNull: false
46+
};
47+
attrs.updatedAt = {
48+
type: Sequelize.BIGINT,
49+
allowNull: false
50+
};
51+
attrs.version = {
52+
type: Sequelize.BIGINT,
53+
allowNull: false
54+
};
55+
console.log('model defined for table: ' + name + '\n' + JSON.stringify(attrs, function (k, v) {
56+
if (k === 'type') {
57+
for (let key in Sequelize) {
58+
if (key === 'ABSTRACT' || key === 'NUMBER') {
59+
continue;
60+
}
61+
let dbType = Sequelize[key];
62+
if (typeof dbType === 'function') {
63+
if (v instanceof dbType) {
64+
if (v._length) {
65+
return `${dbType.key}(${v._length})`;
66+
}
67+
return dbType.key;
68+
}
69+
if (v === dbType) {
70+
return dbType.key;
71+
}
72+
}
73+
}
74+
}
75+
return v;
76+
}, ' '));
77+
return sequelize.define(name, attrs, {
78+
tableName: name,
79+
timestamps: false,
80+
hooks: {
81+
beforeValidate: function (obj) {
82+
let now = Date.now();
83+
if (obj.isNewRecord) {
84+
console.log('will create entity...' + obj);
85+
if (!obj.id) {
86+
obj.id = generateId();
87+
}
88+
obj.createdAt = now;
89+
obj.updatedAt = now;
90+
obj.version = 0;
91+
} else {
92+
console.log('will update entity...');
93+
obj.updatedAt = Date.now();
94+
obj.version++;
95+
}
96+
}
97+
}
98+
});
99+
}
100+
101+
const TYPES = ['STRING', 'INTEGER', 'BIGINT', 'TEXT', 'DOUBLE', 'DATEONLY', 'BOOLEAN'];
102+
103+
var exp = {
104+
defineModel: defineModel,
105+
sync: () => {
106+
// only allow create ddl in non-production environment:
107+
if (process.env.NODE_ENV !== 'production') {
108+
sequelize.sync({ force: true });
109+
} else {
110+
throw new Error('Cannot sync() when NODE_ENV is set to \'production\'.');
111+
}
112+
}
113+
};
114+
115+
for (let type of TYPES) {
116+
exp[type] = Sequelize[type];
117+
}
118+
119+
exp.ID = ID_TYPE;
120+
exp.generateId = generateId;
121+
122+
module.exports = exp;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
require('babel-core/register')({
2+
presets: ['stage-3']
3+
});
4+
5+
const model = require('./model.js');
6+
model.sync();
7+
8+
console.log('init db ok.');
9+
process.exit(0);
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
create database nodejs;
2+
3+
grant all privileges on nodejs.* to 'www'@'%' identified by 'www';
4+
grant all privileges on test.* to 'www'@'%' identified by 'www';
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// scan all models defined in models:
2+
const fs = require('fs');
3+
const db = require('./db');
4+
5+
let files = fs.readdirSync(__dirname + '/models');
6+
7+
let js_files = files.filter((f)=>{
8+
return f.endsWith('.js');
9+
}, files);
10+
11+
module.exports = {};
12+
13+
for (let f of js_files) {
14+
console.log(`import model from file ${f}...`);
15+
let name = f.substring(0, f.length - 3);
16+
module.exports[name] = require(__dirname + '/models/' + f);
17+
}
18+
19+
module.exports.sync = () => {
20+
db.sync();
21+
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const db = require('../db');
2+
3+
module.exports = db.defineModel('pets', {
4+
ownerId: db.ID,
5+
name: db.STRING(100),
6+
gender: db.BOOLEAN,
7+
birth: db.STRING(10),
8+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const db = require('../db');
2+
3+
module.exports = db.defineModel('users', {
4+
email: {
5+
type: db.STRING(100),
6+
unique: true
7+
},
8+
passwd: db.STRING(100),
9+
name: db.STRING(100),
10+
gender: db.BOOLEAN
11+
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "model-sequelize",
3+
"version": "1.0.0",
4+
"description": "Sequelize best practice example with async",
5+
"main": "start.js",
6+
"scripts": {
7+
"start": "node start.js"
8+
},
9+
"keywords": [
10+
"sequelize",
11+
"async"
12+
],
13+
"author": "Michael Liao",
14+
"license": "Apache-2.0",
15+
"repository": {
16+
"type": "git",
17+
"url": "https://github.com/michaelliao/learn-javascript.git"
18+
},
19+
"dependencies": {
20+
"babel-core": "6.13.2",
21+
"babel-polyfill": "6.13.0",
22+
"babel-preset-es2015-node6": "0.3.0",
23+
"babel-preset-stage-3": "6.5.0",
24+
"sequelize": "3.24.1",
25+
"mysql": "2.11.1"
26+
}
27+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
require('babel-core/register')({
2+
presets: ['stage-3']
3+
});
4+
5+
require('./app.js');

0 commit comments

Comments
 (0)