Skip to content

Commit

Permalink
devMode now deprecated
Browse files Browse the repository at this point in the history
  • Loading branch information
DimaCrafter committed Dec 6, 2018
1 parent 9ed3ee0 commit 2fefad6
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 98 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json*
package-lock.json*
13 changes: 3 additions & 10 deletions DB.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const {Schema} = mongoose;
const mongooseAI = require('mongoose-auto-increment');

class DB {
constructor(conf, devMode = false) {
constructor(conf) {
!conf.port && (conf.port = 27017);
const uri = `mongodb://${conf.user?`${conf.user}:${conf.pass}@`:''}${conf.host}:${conf.port}/${conf.name}`;
this.conn = mongoose.createConnection(uri, {
Expand All @@ -16,14 +16,7 @@ class DB {
return new Proxy(this, {
get(obj, name) {
if(name in obj) return obj[name];
if(name in obj.conn.models) {
if(devMode) {
// Removing cached model in devMode
delete obj.conn.models[name];
delete require.cache[require.resolve(`${ROOT}/models/${name}.js`)];
}
else return obj.conn.models[name];
}
if(name in obj.conn.models) return obj.conn.models[name];

let schemaRaw = {...require(`${ROOT}/models/${name}.js`)};
let schemaData = {
Expand Down Expand Up @@ -60,4 +53,4 @@ class DB {
}
}

module.exports = DB;
module.exports = DB;
43 changes: 25 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,32 @@
If you want change `config.json` location or name, you should
change start script to `node node_modules/dc-api-core --cfg /path/to/config.json`

For best development I recommend you to use [nodemon].
You can install this by executing `npm i -g nodemon` or `yarn global add nodemon`.
After this change `node` to `nodemon` in start script in your `package.json`.

---

## config.json

| Variable | Default | Description |
|------------------|---------------|--------------------------------------------------------------|
| `db.host` | Required | Database hostname or IP |
| `db.name` | Required | Database name |
| `db.port` | `27017` | Database port |
| `db.user` | Optional | Database username |
| `db.pass` | | and password |
| | | |
| `session.secret` | Required | Private string for cookie |
| `session.ttl` | `36` | Cookie TTL in hours |
| | | |
| `ssl` | Optional | Enables HTTPS mode if filled |
| `ssl.key` | Required | Local path to private key |
| `ssl.cert` | Required | Local path to certificate file |
| | | |
| `devMode` | `false` | If `true` controllers and models refreshing on every request |
| `port` | `8081` | API listing port |
| `ws_timeout` | `60` | WebSocket request waiting timeout in seconds |
| Variable | Default | Description |
|------------------|---------------------|----------------------------------------------|
| `db.host` | Required | Database hostname or IP |
| `db.name` | Required | Database name |
| `db.port` | `27017` | Database port |
| `db.user` | Optional | Database username |
| `db.pass` | | and password |
| | | |
| `session.secret` | Required | Private string for cookie |
| `session.ttl` | `36` | Cookie TTL in hours |
| | | |
| `ssl` | Optional | Enables HTTPS mode if filled |
| `ssl.key` | Required | Local path to private key |
| `ssl.cert` | Required | Local path to certificate file |
| | | |
| `devMode` | `false` | DEPRECATED, use [nodemon] instead |
| `origin` | `req.get('origin')` | Accept requests only from this origin |
| `port` | `8081` | API listing port |
| `ws_timeout` | `60` | WebSocket request waiting timeout in seconds |

[nodemon]: https://github.com/remy/nodemon
2 changes: 1 addition & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ if(config.ssl) {
if(!config.ssl.cert.startsWith('/')) config.ssl.cert = path.dirname(configPath) + '/' + config.ssl.cert;
if(!config.ssl.key.startsWith('/')) config.ssl.key = path.dirname(configPath) + '/' + config.ssl.key;
}
module.exports = config;
module.exports = config;
31 changes: 11 additions & 20 deletions dispatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,20 @@ const config = require('./config');
const {getHTTPUtils, getWSUtils} = require('./utils');
const path = require('path');
const fs = require('fs');
let loadedControllers = {};

async function getController(controller) {
controller = controller.charAt(0).toUpperCase() + controller.slice(1);
return new Promise((resolve, reject) => {
if (controller in loadedControllers) {
resolve(loadedControllers[controller]);
} else {
const controllerPath = path.normalize(`${ROOT}/controllers/${controller}.js`);
fs.access(controllerPath, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if(err && err.code == 'ENOENT') reject([`API ${controller} controller not found`, 404]);
else if(err) reject([`Can't access ${controller} controller`, 403]);
else {
let controller = require(controllerPath);
controller = new controller();
// Clear cache and don't save controller cache in devMode
config.devMode
? delete require.cache[controllerPath]
: (loadedControllers[controller.constructor.name] = controller);
resolve(controller);
}
});
}
const controllerPath = path.normalize(`${ROOT}/controllers/${controller}.js`);
fs.access(controllerPath, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if(err && err.code == 'ENOENT') reject([`API ${controller} controller not found`, 404]);
else if(err) reject([`Can't access ${controller} controller`, 403]);
else {
let controller = require(controllerPath);
controller = new controller();
resolve(controller);
}
});
});
}

Expand Down Expand Up @@ -83,4 +74,4 @@ const dispatch = {
}
};

module.exports = dispatch;
module.exports = dispatch;
37 changes: 17 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const DB = require('./DB');
(async () => {
try {
console.log(`[DB] Connecting to ${config.db.name} at ${config.db.host}`, config.db.user ? 'as ' + config.db.user : '');
var MainDB = new DB(config.db, config.devMode);
var MainDB = new DB(config.db);
await MainDB.conn;
} catch(err) {
console.log('[DB]', err.name + ':', err.message);
Expand Down Expand Up @@ -49,27 +49,17 @@ const DB = require('./DB');
req.setEncoding('utf8');
req.on('data', chunk => req.body += chunk);
req.on('end', () => {
if(req.body !== '') {
try {
req.body = JSON.parse(req.body);
} catch {
getHTTPUtils(req, res).send('Wrong request', 400);
return;
}
// TODO: type check + file upload support
try {
req.body = JSON.parse(req.body);
} catch {
getHTTPUtils(req, res).send('Wrong request', 400);
return;
}
next();
});
});

// Creating HTTPS server, if ssl enabled
if(config.ssl) {
const https = require('https');
var server = https.createServer({
key: fs.readFileSync(config.ssl.key, 'utf8'),
cert: fs.readFileSync(config.ssl.cert, 'utf8')
}, app);
}

// Dispatching requests
const dispatch = require('./dispatch');
dispatch.db = MainDB;
Expand All @@ -84,6 +74,13 @@ const DB = require('./DB');
() => console.log('[Core] Started' + (config.ssl?' with SSL':'') + ' at port ' + config.port)
];

if(config.ssl) server.listen(...listenArgs);
else app.listen(...listenArgs);
})();
if(config.ssl) {
// Creating HTTPS server, if ssl enabled
const https = require('https');
var server = https.createServer({
key: fs.readFileSync(config.ssl.key, 'utf8'),
cert: fs.readFileSync(config.ssl.cert, 'utf8')
}, app);
server.listen(...listenArgs);
} else app.listen(...listenArgs);
})();
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
{
"name": "dc-api-core",
"version": "0.1.8",
"version": "0.1.8-2",
"author": "DimaCrafter",
"homepage": "https://github.com/DimaCrafter/dc-api-core",
"bugs": "https://github.com/DimaCrafter/dc-api-core/issues",
"repository": "github.com:DimaCrafter/dc-api-core",
"dependencies": {
"connect-mongo": "^2.0.1",
"connect-mongo": "^2.0.3",
"express": "^4.16.4",
"express-session": "^1.15.6",
"express-ws": "^4.0.0",
"mongoose": "^5.3.7",
"mongoose": "^5.3.15",
"mongoose-auto-increment": "^5.0.1"
}
}
8 changes: 5 additions & 3 deletions utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const config = require('./config');
const base = (utils, db, req) => {
return Object.assign(utils, {
db,
Expand All @@ -10,10 +11,11 @@ module.exports = {
getHTTPUtils(req, res, db) {
return base({
send(msg, code = 200) {
res.set('Access-Control-Allow-Origin', req.get('origin'));
res.set('Access-Control-Allow-Origin', config.origin || req.get('origin'));
res.set('Access-Control-Allow-Credentials', 'true');
res.set('Access-Control-Allow-Headers', '*');
res.status(code).json({
res.status(code);
res.json({
success: code === 200,
code,
msg
Expand All @@ -37,4 +39,4 @@ module.exports = {
data: {}
}, db, req);
}
};
};
44 changes: 22 additions & 22 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ body-parser@1.18.3:
raw-body "2.3.3"
type-is "~1.6.16"

bson@^1.1.0:
bson@^1.1.0, bson@~1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/bson/-/bson-1.1.0.tgz#bee57d1fb6a87713471af4e32bcae36de814b5b0"
integrity sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA==

bson@~1.0.4, bson@~1.0.5:
bson@~1.0.4:
version "1.0.9"
resolved "https://registry.yarnpkg.com/bson/-/bson-1.0.9.tgz#12319f8323b1254739b7c6bef8d3e89ae05a2f57"
integrity sha512-IQX9/h7WdMBIW/q/++tGd+emQr0XMdeZ6icnT/74Xk9fnabWn+gZgpE+9V+gujL3hhJOoNrnDVY7tWdzc7NUTg==
Expand All @@ -68,10 +68,10 @@ bytes@3.0.0:
resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048"
integrity sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=

connect-mongo@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/connect-mongo/-/connect-mongo-2.0.1.tgz#514d649cff1d5d5546c087193245bb54ff5b703b"
integrity sha512-ghBvVq0SA0SkTFsbAB8HdF1+uoHdFJICSlrTklNloMKXuRpX9IuVBnG0DlKnXBZSQI0Joyaq22cazsrV9+5g2A==
connect-mongo@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/connect-mongo/-/connect-mongo-2.0.3.tgz#db6cabe1e3add5acc9ef9c486681027675a58ee5"
integrity sha512-Vs+QZ/6X6gbCrP1Ls7Oh/wlyY6pgpbPSrUKF5yRT+zd+4GZPNbjNquxquZ+Clv2+03HBXE7T4lVM0PUcaBhihg==
dependencies:
mongodb "^2.0.36"

Expand Down Expand Up @@ -332,23 +332,23 @@ mongodb-core@2.1.20:
bson "~1.0.4"
require_optional "~1.0.0"

mongodb-core@3.1.5:
version "3.1.5"
resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-3.1.5.tgz#59ca67d7f6cea570d5437624a7afec8d752d477a"
integrity sha512-emT/tM4ZBinqd6RZok+EzDdtN4LjYJIckv71qQVOEFmvXgT5cperZegVmTgox/1cx4XQu6LJ5ZuIwipP/eKdQg==
mongodb-core@3.1.9:
version "3.1.9"
resolved "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-3.1.9.tgz#c31ee407bf932b0149eaed775c17ee09974e4ca3"
integrity sha512-MJpciDABXMchrZphh3vMcqu8hkNf/Mi+Gk6btOimVg1XMxLXh87j6FAvRm+KmwD1A9fpu3qRQYcbQe4egj23og==
dependencies:
bson "^1.1.0"
require_optional "^1.0.1"
safe-buffer "^5.1.2"
optionalDependencies:
saslprep "^1.0.0"

mongodb@3.1.6:
version "3.1.6"
resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-3.1.6.tgz#6054641973b5bf5b5ae1c67dcbcf8fa88280273d"
integrity sha512-E5QJuXQoMlT7KyCYqNNMfAkhfQD79AT4F8Xd+6x37OX+8BL17GyXyWvfm6wuyx4wnzCCPoCSLeMeUN2S7dU9yw==
mongodb@3.1.10:
version "3.1.10"
resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-3.1.10.tgz#45ad9b74ea376f4122d0881b75e5489b9e504ed7"
integrity sha512-Uml42GeFxhTGQVml1XQ4cD0o/rp7J2ROy0fdYUcVitoE7vFqEhKH4TYVqRDpQr/bXtCJVxJdNQC1ntRxNREkPQ==
dependencies:
mongodb-core "3.1.5"
mongodb-core "3.1.9"
safe-buffer "^5.1.2"

mongodb@^2.0.36:
Expand All @@ -372,17 +372,17 @@ mongoose-legacy-pluralize@1.0.2:
resolved "https://registry.yarnpkg.com/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz#3ba9f91fa507b5186d399fb40854bff18fb563e4"
integrity sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==

mongoose@^5.3.4:
version "5.3.4"
resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-5.3.4.tgz#acd02fae9c1bcd723d3df7d96109f57c38f74919"
integrity sha512-DIUWOyYgZv2zGi/BoFEaFiaCVuDonnzGhW3cnc3JFjBScYn6z24tS2j3VB0dtMoX8FFjxmmMVnlmHPEIbV4PKA==
mongoose@^5.3.14:
version "5.3.14"
resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-5.3.14.tgz#14fb782423561187e8e4264deb9e213156ca3ea6"
integrity sha512-Vt7uC0+/SuPb+x6IwbtXl4tkUER1xU9INlfrDK1RdfsvvEMfG3FJUGNPVGeTWQaj8xqMBtZKIdUNt58rIAsCYg==
dependencies:
async "2.6.1"
bson "~1.0.5"
bson "~1.1.0"
kareem "2.3.0"
lodash.get "4.4.2"
mongodb "3.1.6"
mongodb-core "3.1.5"
mongodb "3.1.10"
mongodb-core "3.1.9"
mongoose-legacy-pluralize "1.0.2"
mpath "0.5.1"
mquery "3.2.0"
Expand Down

0 comments on commit 2fefad6

Please sign in to comment.