Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use stream #62

Merged
merged 1 commit into from
Oct 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const Schema = require('./schema');
const SchemaType = require('./schematype');
const WarehouseError = require('./error');
const pkg = require('../package.json');
const JsonReadable = require('json-stream-stringify');

class Database {

Expand Down Expand Up @@ -112,12 +111,43 @@ class Database {

if (!path) throw new WarehouseError('options.path is required');

const rs = new JsonReadable(this);
return new Promise((resolve, reject) => {
const stream = fs.createWriteStream(path);

const ws = fs.createWriteStream(path);
// Start
stream.write('{');

return new Promise((resolve, reject) => {
rs.once('error', reject).pipe(ws).once('error', reject).once('finish', resolve);
// Meta
stream.write(`"meta":${JSON.stringify({
version: this.options.version,
warehouse: pkg.version
})},`);

// Export models

stream.write('"models":{');

const models = this._models;
const keys = Object.keys(models);
const { length } = keys;

for (let i = 0; i < length; i++) {
const key = keys[i];
const model = models[key];

if (!model) continue;

if (i) stream.write(',');
stream.write(`"${key}":${model._export()}`);
}

stream.write('}');

// End
stream.end('}');

stream.on('error', reject)
.on('finish', resolve);
}).asCallback(callback);
}

Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"cuid": "^2.1.4",
"graceful-fs": "^4.1.3",
"is-plain-object": "^3.0.0",
"json-stream-stringify": "^2.0.0",
"lodash": "^4.17.10"
},
"devDependencies": {
Expand Down