json-file-database
Version:
Lightweight Database on NodeJS by JSON Files
84 lines (83 loc) • 3.04 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const src_1 = require("../src");
const shared_1 = require("./shared");
const test = ava_1.default;
test.beforeEach((t) => {
const db = (0, shared_1.connectDatabase)();
t.context.objs = db({
name: 'objs',
primaryKey: 'id',
});
});
test('insert', (t) => {
const { objs } = t.context;
t.false(objs.insert({ id: 123, name: 'Liu Zhao' }));
t.true(objs.insert({ id: 114514, name: 'Koji Tadokoro' }));
t.false(objs.insert({ id: 114514, name: 'Koji Tadokoro' }));
});
test('list', (t) => {
const { objs } = t.context;
t.deepEqual(Array.from(objs), shared_1.OBJS_ARRAY);
});
test('update', (t) => {
const { objs } = t.context;
t.true(objs.update({ id: 123, name: 'Liu Zhao' }));
t.deepEqual(objs.find({ id: 123 }), { id: 123, name: 'Liu Zhao' });
t.true(objs.update({ id: 123, name: 'Koji Tadokoro' }));
t.deepEqual(objs.find({ id: 123 }), { id: 123, name: 'Koji Tadokoro' });
});
test('find-and-has', (t) => {
const { objs } = t.context;
t.deepEqual(objs.find({ id: 123 }), { id: 123, name: 'San Zhang' });
t.true(objs.has({ id: 456 }));
t.true(objs.has(o => o.name === 'Wu Wang'));
t.false(objs.has({ id: 114514 }));
});
test('remove', (t) => {
const { objs } = t.context;
t.true(objs.remove({ id: 123 }));
t.false(objs.remove({ id: 123 }));
t.true(objs.remove({ id: 456 }));
t.deepEqual([...objs].length, 1);
});
test('sort', (t) => {
const numsArr = [63, 3, 57, 7, 62, 9];
const insertArr = [77, 23, 6, 56];
const db = (0, src_1.connect)({
file: (0, src_1.createObjectFile)({
nums: numsArr.map(item => ({ id: item })),
}),
});
const nums = db({
name: 'nums',
primaryKey: 'id',
comparator: (first, second) => Number(second.id) - Number(first.id),
});
insertArr.forEach(i => nums.insert({ id: i }));
const expected = numsArr.concat(insertArr).sort((a, b) => b - a);
const actual = Array.from(nums).map(n => n.id);
t.deepEqual(actual, expected);
});
test('string-id', (t) => {
const wordsArr = ['the', 'quick', 'brown', 'fox', 'jumps'];
// "over the lazy dog", here we don't use "the" to make elements unique.
const insertArr = ['over', 'lazy', 'dog'];
const db = (0, src_1.connect)({
file: (0, src_1.createObjectFile)({
words: wordsArr.map(w => ({ id: w })),
}),
});
const words = db({
name: 'words',
primaryKey: 'id',
});
insertArr.forEach(i => words.insert({ id: i }));
const expected = wordsArr.concat(insertArr).sort();
const actual = Array.from(words).map(w => w.id);
t.deepEqual(expected, actual);
});