Skip to content

Commit

Permalink
Merge 0e23108 into e0d4503
Browse files Browse the repository at this point in the history
  • Loading branch information
segayuu committed Aug 12, 2022
2 parents e0d4503 + 0e23108 commit 58a550f
Show file tree
Hide file tree
Showing 50 changed files with 629 additions and 567 deletions.
15 changes: 13 additions & 2 deletions .eslintrc.json
@@ -1,4 +1,15 @@
{
"root": true,
"extends": "hexo"
}
"extends": "hexo/ts.js",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2020
},
"rules": {
"@typescript-eslint/no-unused-vars": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/ban-ts-comment": 0,
"no-use-before-define": 0
}
}
3 changes: 2 additions & 1 deletion .gitignore
Expand Up @@ -4,4 +4,5 @@ node_modules/
.nyc_output/
*.log
docs/
coverage/
coverage/
dist
14 changes: 0 additions & 14 deletions lib/types/index.js

This file was deleted.

47 changes: 31 additions & 16 deletions package.json
Expand Up @@ -2,18 +2,21 @@
"name": "warehouse",
"version": "4.0.1",
"description": "Simple JSON-based database",
"main": "lib/database",
"main": "dist/database",
"directories": {
"lib": "./lib"
"lib": "./dist"
},
"files": [
"lib/"
"dist/"
],
"scripts": {
"eslint": "eslint lib test",
"test": "mocha \"test/scripts/**/*.js\"",
"pretest": "npm run typescript",
"typescript": "tsc --build tsconfig.json",
"eslint": "eslint src test",
"test": "mocha -r ts-node/register 'test/scripts/**/*.ts'",
"test-cov": "nyc --reporter=lcovonly --reporter=text-summary npm test",
"jsdoc": "jsdoc --configure .jsdoc.json"
"jsdoc": "jsdoc --configure .jsdoc.json",
"prepublish": "npm run typescript"
},
"repository": "hexojs/warehouse",
"keywords": [
Expand All @@ -24,26 +27,38 @@
"author": "Tommy Chen <tommy351@gmail.com> (http://zespia.tw)",
"license": "MIT",
"dependencies": {
"bluebird": "^3.2.2",
"cuid": "^2.1.4",
"graceful-fs": "^4.1.3",
"@types/through2": "^2.0.36",
"bluebird": "^3.7.2",
"cuid": "^2.1.8",
"graceful-fs": "^4.2.10",
"hexo-log": "^3.0.0",
"is-plain-object": "^5.0.0",
"jsonparse": "^1.3.1",
"rfdc": "^1.1.4",
"rfdc": "^1.3.0",
"through2": "^4.0.2"
},
"devDependencies": {
"chai": "^4.2.0",
"@types/bluebird": "^3.5.36",
"@types/chai": "^4.3.1",
"@types/graceful-fs": "^4.1.5",
"@types/jsonstream": "^0.8.30",
"@types/mocha": "^9.1.1",
"@types/node": "^18.0.0",
"@types/sinon": "^10.0.11",
"@typescript-eslint/eslint-plugin": "^5.29.0",
"@typescript-eslint/parser": "^5.29.0",
"chai": "^4.3.6",
"chai-as-promised": "^7.1.1",
"eslint": "^8.1.0",
"eslint": "^8.18.0",
"eslint-config-hexo": "^5.0.0",
"jsdoc": "^3.4.0",
"lodash": "^4.17.15",
"minami": "^1.1.1",
"jsdoc": "^3.6.10",
"lodash": "^4.17.21",
"minami": "^1.2.3",
"mocha": "^10.0.0",
"nyc": "^15.0.0",
"sinon": "^14.0.0"
"sinon": "^14.0.0",
"ts-node": "^10.8.1",
"typescript": "^4.7.4"
},
"engines": {
"node": ">=14"
Expand Down
73 changes: 44 additions & 29 deletions lib/database.js → src/database.ts
@@ -1,28 +1,28 @@
'use strict';

const { parse: createJsonParseStream } = require('./jsonstream');
const Promise = require('bluebird');
const fs = require('graceful-fs');
const Model = require('./model');
const Schema = require('./schema');
const SchemaType = require('./schematype');
const WarehouseError = require('./error');
import { parse as createJsonParseStream } from './lib/jsonstream';
import Bluebird from 'bluebird';
import { writev, promises as fsPromises, createReadStream } from 'graceful-fs';
import { pipeline, Stream } from 'stream';
import Model from './model';
import Schema from './schema';
import SchemaType from './schematype';
import WarehouseError from './error';
import log from 'hexo-log';

const pkg = require('../package.json');
const { open } = fs.promises;
const pipeline = Promise.promisify(require('stream').pipeline);
const log = require('hexo-log')();
const { open } = fsPromises;
const pipelineAsync = Bluebird.promisify(pipeline) as (...args: Stream[]) => Bluebird<unknown>;

let _writev;
let _writev: (handle: fsPromises.FileHandle, buffers: Buffer[]) => Promise<unknown>;

if (typeof fs.writev === 'function') {
if (typeof writev === 'function') {
_writev = (handle, buffers) => handle.writev(buffers);
} else {
_writev = async (handle, buffers) => {
for (const buffer of buffers) await handle.write(buffer);
};
}

async function exportAsync(database, path) {
async function exportAsync(database: Database, path: string) {
const handle = await open(path, 'w');

try {
Expand Down Expand Up @@ -69,7 +69,17 @@ async function exportAsync(database, path) {
}
}

interface DatabaseOptions {
version: number,
path: string,
onUpgrade: (...args: any[]) => any,
onDowngrade: (...args: any[]) => any
}

class Database {
options: DatabaseOptions;
_models: any;
Model: typeof Model;

/**
* Database constructor.
Expand All @@ -80,13 +90,15 @@ class Database {
* @param {function} [options.onUpgrade] Triggered when the database is upgraded
* @param {function} [options.onDowngrade] Triggered when the database is downgraded
*/
constructor(options) {
this.options = Object.assign({
constructor(options?: { path: string } & Partial<DatabaseOptions>) {
this.options = {
version: 0,
// eslint-disable-next-line @typescript-eslint/no-empty-function
onUpgrade() {},

onDowngrade() {}
}, options);
// eslint-disable-next-line @typescript-eslint/no-empty-function
onDowngrade() {},
...options
};

this._models = {};

Expand All @@ -104,7 +116,7 @@ class Database {
* @param {Schema|object} [schema]
* @return {Model}
*/
model(name, schema) {
model(name: string, schema?: any) {
if (this._models[name]) {
return this._models[name];
}
Expand All @@ -120,7 +132,7 @@ class Database {
* @param {function} [callback]
* @return {Promise}
*/
load(callback) {
load(callback?) {
const { path, onUpgrade, onDowngrade, version: newVersion } = this.options;

if (!path) throw new WarehouseError('options.path is required');
Expand All @@ -143,9 +155,9 @@ class Database {
this.model(data.key)._import(data.value);
});

const rs = fs.createReadStream(path, 'utf8');
const rs = createReadStream(path, 'utf8');

return pipeline(rs, parseStream).then(() => {
return pipelineAsync(rs, parseStream).then(() => {
if (newVersion > oldVersion) {
return onUpgrade(oldVersion, newVersion);
} else if (newVersion < oldVersion) {
Expand All @@ -160,11 +172,11 @@ class Database {
* @param {function} [callback]
* @return {Promise}
*/
save(callback) {
save(callback?) {
const { path } = this.options;

if (!path) throw new WarehouseError('options.path is required');
return Promise.resolve(exportAsync(this, path)).asCallback(callback);
return Bluebird.resolve(exportAsync(this, path)).asCallback(callback);
}

toJSON() {
Expand All @@ -182,12 +194,15 @@ class Database {
}, models
};
}
static Schema = Schema;
Schema: typeof Schema;
static SchemaType = SchemaType;
SchemaType: typeof SchemaType;
static version: number;
}

Database.prototype.Schema = Schema;
Database.Schema = Database.prototype.Schema;
Database.prototype.SchemaType = SchemaType;
Database.SchemaType = Database.prototype.SchemaType;
Database.version = pkg.version;

module.exports = Database;
export default Database;
12 changes: 7 additions & 5 deletions lib/document.js → src/document.ts
@@ -1,8 +1,10 @@
'use strict';
import rfdc from 'rfdc';
const cloneDeep = rfdc();

const cloneDeep = require('rfdc')();

class Document {
abstract class Document {
abstract _model;
_id!: any;
abstract _schema;

/**
* Document constructor.
Expand Down Expand Up @@ -101,4 +103,4 @@ function isGetter(obj, key) {
return Object.getOwnPropertyDescriptor(obj, key).get;
}

module.exports = Document;
export default Document;
13 changes: 6 additions & 7 deletions lib/error.js → src/error.ts
@@ -1,25 +1,24 @@
'use strict';

class WarehouseError extends Error {
code?: string;

/**
* WarehouseError constructor
*
* @param {string} msg
* @param {string} code
*/
constructor(msg, code) {
constructor(msg: string, code?: string) {
super(msg);

Error.captureStackTrace(this);

this.code = code;
}
static ID_EXIST = 'ID_EXIST';
static ID_NOT_EXIST = 'ID_NOT_EXIST';
static ID_UNDEFINED = 'ID_UNDEFINED';
}

WarehouseError.prototype.name = 'WarehouseError';
WarehouseError.ID_EXIST = 'ID_EXIST';
WarehouseError.ID_NOT_EXIST = 'ID_NOT_EXIST';
WarehouseError.ID_UNDEFINED = 'ID_UNDEFINED';

module.exports = WarehouseError;
export default WarehouseError;
6 changes: 2 additions & 4 deletions lib/error/population.js → src/error/population.ts
@@ -1,9 +1,7 @@
'use strict';

const WarehouseError = require('../error');
import WarehouseError from '../error';

class PopulationError extends WarehouseError {}

PopulationError.prototype.name = 'PopulationError';

module.exports = PopulationError;
export default PopulationError;
6 changes: 2 additions & 4 deletions lib/error/validation.js → src/error/validation.ts
@@ -1,9 +1,7 @@
'use strict';

const WarehouseError = require('../error');
import WarehouseError from '../error';

class ValidationError extends WarehouseError {}

ValidationError.prototype.name = 'ValidationError';

module.exports = ValidationError;
export default ValidationError;
15 changes: 9 additions & 6 deletions lib/jsonstream/index.js → src/lib/jsonstream/index.ts
@@ -1,7 +1,5 @@
'use strict';

const through2 = require('through2');
const Parser = require('jsonparse');
import through2 from 'through2';
import Parser from 'jsonparse';

/**
* Check whether a x and y are equal, or x matches y, or x(y) is truthy.
Expand Down Expand Up @@ -29,7 +27,7 @@ const check = (x, y) => {
return false;
};

module.exports.parse = function(path, map) {
export function parse(path, map = null) {
let header, footer;

const parser = new Parser();
Expand All @@ -50,6 +48,7 @@ module.exports.parse = function(path, map) {
}

if (parser.tState !== Parser.C.START || parser.stack.length > 0) {
// @ts-ignore
cb(new Error('Incomplete JSON'));
return;
}
Expand Down Expand Up @@ -80,6 +79,7 @@ module.exports.parse = function(path, map) {
}

parser.onValue = function(value) {
// @ts-ignore
if (!this.root) { stream.root = value; }

if (!path) return;
Expand Down Expand Up @@ -169,9 +169,12 @@ module.exports.parse = function(path, map) {
parser.onToken = function(token, value) {
parser._onToken(token, value);
if (this.stack.length === 0) {
// @ts-ignore
if (stream.root) {
// @ts-ignore
if (!path) { stream.push(stream.root); }

// @ts-ignore
stream.root = null;
}
}
Expand Down Expand Up @@ -199,4 +202,4 @@ module.exports.parse = function(path, map) {
footer[key] = value;
}
}
};
}

0 comments on commit 58a550f

Please sign in to comment.