mirror of
https://gitlab.com/CIEFWorldwideSdnBhd/izyim-mockapi.git
synced 2026-08-21 13:34:26 +00:00
added necessary npm packages
This commit is contained in:
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"presets": [
|
||||
"es2015",
|
||||
"stage-3"
|
||||
]
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
.travis.yml
|
||||
src
|
||||
test
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 typicode
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
# Lowdb [](http://badge.fury.io/js/lowdb) [](https://travis-ci.org/typicode/lowdb)
|
||||
|
||||
> A small local database powered by lodash API
|
||||
|
||||
```js
|
||||
const db = low('db.json')
|
||||
|
||||
// Set some defaults if your JSON file is empty
|
||||
db.defaults({ posts: [], user: {} })
|
||||
.write()
|
||||
|
||||
// Add a post
|
||||
db.get('posts')
|
||||
.push({ id: 1, title: 'lowdb is awesome'})
|
||||
.write()
|
||||
|
||||
// Set a user
|
||||
db.set('user.name', 'typicode')
|
||||
.value()
|
||||
```
|
||||
|
||||
Data is saved to `db.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"posts": [
|
||||
{ "id": 1, "title": "lowdb is awesome"}
|
||||
],
|
||||
"user": {
|
||||
"name": "typicode"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can use any [lodash](https://lodash.com/docs) function like `_.get` and `_.find` with shorthand syntax.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.find({ id: 1 })
|
||||
.value()
|
||||
```
|
||||
|
||||
Lowdb is perfect for CLIs, small servers, Electron apps and npm packages in general.
|
||||
|
||||
It supports __Node__, the __browser__ and uses __lodash API__, so it's very simple to learn. Actually... you may already know how to use lowdb :wink:
|
||||
|
||||
* [Usage examples](https://github.com/typicode/lowdb/tree/master/examples)
|
||||
* [CLI](https://github.com/typicode/lowdb/tree/master/examples#cli)
|
||||
* [Browser](https://github.com/typicode/lowdb/tree/master/examples#browser)
|
||||
* [Server](https://github.com/typicode/lowdb/tree/master/examples#server)
|
||||
* [In-memory](https://github.com/typicode/lowdb/tree/master/examples#in-memory)
|
||||
* [JSFiddle live example](https://jsfiddle.net/typicode/4kd7xxbu/)
|
||||
* [__Migrating from 0.14 to 0.15? See this guide.__](https://github.com/typicode/lowdb/releases/tag/v0.15.0)
|
||||
|
||||
## Why lowdb?
|
||||
|
||||
* Lodash API
|
||||
* Minimal and simple to use
|
||||
* Highly flexible
|
||||
* __Custom storage__ (file, browser, in-memory, ...)
|
||||
* __Custom format__ (JSON, BSON, YAML, XML, ...)
|
||||
* Mixins (id support, ...)
|
||||
* Read-only or write-only modes
|
||||
* Encryption
|
||||
|
||||
__Important__ lowdb doesn't support Cluster.
|
||||
|
||||
## Used by
|
||||
|
||||
* [felony](https://github.com/henryboldi/felony)
|
||||
* [googlesamples/md2googleslides](https://github.com/googlesamples/md2googleslides)
|
||||
* [fb-sleep-stats](https://github.com/sqren/fb-sleep-stats)
|
||||
* [kadirahq/storybook-database-local](https://github.com/kadirahq/storybook-database-local)
|
||||
* [json-server](https://github.com/typicode/json-server)
|
||||
* ... and [other awesome projects](https://www.npmjs.com/browse/depended/lowdb)
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install lowdb --save
|
||||
```
|
||||
|
||||
Alternatively, if you're using [yarn](https://yarnpkg.com/)
|
||||
|
||||
```sh
|
||||
yarn add lowdb
|
||||
```
|
||||
|
||||
A UMD build is also available on [unpkg](https://unpkg.com/) for testing and quick prototyping:
|
||||
|
||||
```html
|
||||
<script src="https://unpkg.com/lodash@4/lodash.min.js"></script>
|
||||
<script src="https://unpkg.com/lowdb/dist/lowdb.min.js"></script>
|
||||
<script>
|
||||
var db = low('db')
|
||||
</script>
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
__low([source, [options])__
|
||||
|
||||
* `source` string or null, will be passed to storage
|
||||
* `options` object
|
||||
* `storage` object, by default `lowdb/lib/storages/file-sync` or `lowdb/lib/storages/browser`.
|
||||
* `read` function
|
||||
* `write` function
|
||||
* `format` object
|
||||
* `serialize` function, by default `JSON.stringify`
|
||||
* `deserialize` function, by default `JSON.parse`
|
||||
|
||||
Creates a __lodash chain__, you can use __any__ lodash method on it. When `.value()` is called data is saved using `storage`.
|
||||
|
||||
You can use `options` to configure how lowdb should persist data. Here are some examples:
|
||||
|
||||
```js
|
||||
// in-memory
|
||||
low()
|
||||
|
||||
// persisted using async file storage
|
||||
low('db.json', { storage: require('lowdb/lib/storages/file-async') })
|
||||
|
||||
// persisted using a custom storage
|
||||
low('some-source', { storage: require('./my-custom-storage') })
|
||||
|
||||
// read-only
|
||||
const fileSync = require('lowdb/lib/storages/file-sync')
|
||||
low('db.json', {
|
||||
storage: {
|
||||
read: fileSync.read
|
||||
}
|
||||
})
|
||||
|
||||
// write-only
|
||||
low('db.json', {
|
||||
storage: {
|
||||
write: fileSync.write
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
__db.___
|
||||
|
||||
Database lodash instance. Use it to add your own utility functions or third-party mixins like [underscore-contrib](https://github.com/documentcloud/underscore-contrib) or [underscore-db](https://github.com/typicode/underscore-db).
|
||||
|
||||
```js
|
||||
db._.mixin({
|
||||
second: function(array) {
|
||||
return array[1]
|
||||
}
|
||||
})
|
||||
|
||||
const post1 = db.get('posts').first().value()
|
||||
const post2 = db.get('posts').second().value()
|
||||
```
|
||||
|
||||
__db.getState()__
|
||||
|
||||
Use whenever you want to access the database state.
|
||||
|
||||
```js
|
||||
db.getState() // { posts: [ ... ] }
|
||||
```
|
||||
|
||||
__db.setState(newState)__
|
||||
|
||||
Use it to drop database or set a new state (database will be automatically persisted).
|
||||
|
||||
```js
|
||||
const newState = {}
|
||||
db.setState(newState)
|
||||
```
|
||||
|
||||
__db.write([source])__
|
||||
|
||||
Persists database using `storage.write` option. Depending on the storage, it may return a promise (for example, with `file-async`).
|
||||
|
||||
By default, lowdb automatically calls it when database changes.
|
||||
|
||||
```js
|
||||
const db = low('db.json')
|
||||
db.write() // writes to db.json
|
||||
db.write('copy.json') // writes to copy.json
|
||||
```
|
||||
|
||||
__db.read([source])__
|
||||
|
||||
Reads source using `storage.read` option. Depending on the storage, it may return a promise.
|
||||
|
||||
```js
|
||||
const db = low('db.json')
|
||||
db.read() // reads db.json
|
||||
db.read('copy.json') // reads copy.json
|
||||
```
|
||||
|
||||
## Guide
|
||||
|
||||
### How to query
|
||||
|
||||
With lowdb, you get access to the entire [lodash API](http://lodash.com/), so there are many ways to query and manipulate data. Here are a few examples to get you started.
|
||||
|
||||
Please note that data is returned by reference, this means that modifications to returned objects may change the database. To avoid such behaviour, you need to use `.cloneDeep()`.
|
||||
|
||||
Also, the execution of methods is lazy, that is, execution is deferred until `.value()` is called.
|
||||
|
||||
#### Examples
|
||||
|
||||
Check if posts exists.
|
||||
|
||||
```js
|
||||
db.has('posts')
|
||||
.value()
|
||||
```
|
||||
|
||||
Set posts.
|
||||
|
||||
```js
|
||||
db.set('posts', [])
|
||||
.write()
|
||||
```
|
||||
|
||||
|
||||
Sort the top five posts.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.filter({published: true})
|
||||
.sortBy('views')
|
||||
.take(5)
|
||||
.value()
|
||||
```
|
||||
|
||||
Get post titles.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.map('title')
|
||||
.value()
|
||||
```
|
||||
|
||||
Get the number of posts.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.size()
|
||||
.value()
|
||||
```
|
||||
|
||||
Get the title of first post using a path.
|
||||
|
||||
```js
|
||||
db.get('posts[0].title')
|
||||
.value()
|
||||
```
|
||||
|
||||
Update a post.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.find({ title: 'low!' })
|
||||
.assign({ title: 'hi!'})
|
||||
.write()
|
||||
```
|
||||
|
||||
Remove posts.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.remove({ title: 'low!' })
|
||||
.write()
|
||||
```
|
||||
|
||||
Remove a property.
|
||||
|
||||
```js
|
||||
db.unset('user.name')
|
||||
.write()
|
||||
```
|
||||
|
||||
Make a deep clone of posts.
|
||||
|
||||
```js
|
||||
db.get('posts')
|
||||
.cloneDeep()
|
||||
.value()
|
||||
```
|
||||
|
||||
|
||||
### How to use id based resources
|
||||
|
||||
Being able to get data using an id can be quite useful, particularly in servers. To add id-based resources support to lowdb, you have 2 options.
|
||||
|
||||
[underscore-db](https://github.com/typicode/underscore-db) provides a set of helpers for creating and manipulating id-based resources.
|
||||
|
||||
```js
|
||||
const db = low('db.json')
|
||||
|
||||
db._.mixin(require('underscore-db'))
|
||||
|
||||
const postId = db.get('posts').insert({ title: 'low!' }).write().id
|
||||
const post = db.get('posts').getById(postId).value()
|
||||
```
|
||||
|
||||
[uuid](https://github.com/broofa/node-uuid) is more minimalist and returns a unique id that you can use when creating resources.
|
||||
|
||||
```js
|
||||
const uuid = require('uuid')
|
||||
|
||||
const postId = db.get('posts').push({ id: uuid(), title: 'low!' }).write().id
|
||||
const post = db.get('posts').find({ id: postId }).value()
|
||||
```
|
||||
|
||||
### How to use a custom storage or format
|
||||
|
||||
`low()` accepts custom storage or format. Simply create objects with `read/write` or `serialize/deserialize` methods. See `src/browser.js` code source for a full example.
|
||||
|
||||
```js
|
||||
const myStorage = {
|
||||
read: (source, deserialize) => // must return an object or a Promise
|
||||
write: (source, obj, serialize) => // must return undefined or a Promise
|
||||
}
|
||||
|
||||
const myFormat = {
|
||||
serialize: (obj) => // must return data (usually string)
|
||||
deserialize: (data) => // must return an object
|
||||
}
|
||||
|
||||
low(source, {
|
||||
storage: myStorage,
|
||||
format: myFormat
|
||||
})
|
||||
```
|
||||
|
||||
### How to encrypt data
|
||||
|
||||
Simply `encrypt` and `decrypt` data in `format.serialize` and `format.deserialize` methods.
|
||||
|
||||
For example, using [cryptr](https://github.com/MauriceButler/cryptr):
|
||||
|
||||
```js
|
||||
const Cryptr = require("./cryptr"),
|
||||
const cryptr = new Cryptr('my secret key')
|
||||
|
||||
const db = low('db.json', {
|
||||
format: {
|
||||
deserialize: (str) => {
|
||||
const decrypted = cryptr.decrypt(str)
|
||||
const obj = JSON.parse(decrypted)
|
||||
return obj
|
||||
},
|
||||
serialize: (obj) => {
|
||||
const str = JSON.stringify(obj)
|
||||
const encrypted = cryptr.encrypt(str)
|
||||
return encrypted
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Changelog
|
||||
|
||||
See changes for each version in the [release notes](https://github.com/typicode/lowdb/releases).
|
||||
|
||||
## Limits
|
||||
|
||||
lowdb is a convenient method for storing data without setting up a database server. It is fast enough and safe to be used as an embedded database.
|
||||
|
||||
However, if you seek high performance and scalability more than simplicity, you should probably stick to traditional databases like MongoDB.
|
||||
|
||||
## License
|
||||
|
||||
MIT - [Typicode](https://github.com/typicode)
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
/*! lowdb v0.15.5 */
|
||||
var low =
|
||||
/******/ (function(modules) { // webpackBootstrap
|
||||
/******/ // The module cache
|
||||
/******/ var installedModules = {};
|
||||
|
||||
/******/ // The require function
|
||||
/******/ function __webpack_require__(moduleId) {
|
||||
|
||||
/******/ // Check if module is in cache
|
||||
/******/ if(installedModules[moduleId])
|
||||
/******/ return installedModules[moduleId].exports;
|
||||
|
||||
/******/ // Create a new module (and put it into the cache)
|
||||
/******/ var module = installedModules[moduleId] = {
|
||||
/******/ i: moduleId,
|
||||
/******/ l: false,
|
||||
/******/ exports: {}
|
||||
/******/ };
|
||||
|
||||
/******/ // Execute the module function
|
||||
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
|
||||
|
||||
/******/ // Flag the module as loaded
|
||||
/******/ module.l = true;
|
||||
|
||||
/******/ // Return the exports of the module
|
||||
/******/ return module.exports;
|
||||
/******/ }
|
||||
|
||||
|
||||
/******/ // expose the modules object (__webpack_modules__)
|
||||
/******/ __webpack_require__.m = modules;
|
||||
|
||||
/******/ // expose the module cache
|
||||
/******/ __webpack_require__.c = installedModules;
|
||||
|
||||
/******/ // identity function for calling harmony imports with the correct context
|
||||
/******/ __webpack_require__.i = function(value) { return value; };
|
||||
|
||||
/******/ // define getter function for harmony exports
|
||||
/******/ __webpack_require__.d = function(exports, name, getter) {
|
||||
/******/ if(!__webpack_require__.o(exports, name)) {
|
||||
/******/ Object.defineProperty(exports, name, {
|
||||
/******/ configurable: false,
|
||||
/******/ enumerable: true,
|
||||
/******/ get: getter
|
||||
/******/ });
|
||||
/******/ }
|
||||
/******/ };
|
||||
|
||||
/******/ // getDefaultExport function for compatibility with non-harmony modules
|
||||
/******/ __webpack_require__.n = function(module) {
|
||||
/******/ var getter = module && module.__esModule ?
|
||||
/******/ function getDefault() { return module['default']; } :
|
||||
/******/ function getModuleExports() { return module; };
|
||||
/******/ __webpack_require__.d(getter, 'a', getter);
|
||||
/******/ return getter;
|
||||
/******/ };
|
||||
|
||||
/******/ // Object.prototype.hasOwnProperty.call
|
||||
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
|
||||
|
||||
/******/ // __webpack_public_path__
|
||||
/******/ __webpack_require__.p = "";
|
||||
|
||||
/******/ // Load entry module and return exports
|
||||
/******/ return __webpack_require__(__webpack_require__.s = 5);
|
||||
/******/ })
|
||||
/************************************************************************/
|
||||
/******/ ([
|
||||
/* 0 */
|
||||
/***/ (function(module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
|
||||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
||||
|
||||
var isPromise = __webpack_require__(4);
|
||||
var memory = __webpack_require__(3);
|
||||
var defaultStorage = __webpack_require__(2);
|
||||
|
||||
var init = function init(db, key, source) {
|
||||
var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
|
||||
_ref$storage = _ref.storage,
|
||||
storage = _ref$storage === undefined ? defaultStorage : _ref$storage,
|
||||
_ref$format = _ref.format,
|
||||
format = _ref$format === undefined ? {} : _ref$format;
|
||||
|
||||
db.source = source;
|
||||
|
||||
// Set storage
|
||||
// In-memory only if no source is provided
|
||||
db.storage = _extends({}, memory, db.source && storage);
|
||||
|
||||
db.read = function () {
|
||||
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : source;
|
||||
|
||||
var r = db.storage.read(s, format.deserialize);
|
||||
|
||||
return isPromise(r) ? r.then(db.plant) : db.plant(r);
|
||||
};
|
||||
|
||||
db.write = function () {
|
||||
var dest = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : source;
|
||||
|
||||
var value = (arguments.length <= 1 ? 0 : arguments.length - 1) ? arguments.length <= 1 ? undefined : arguments[1] : db.getState();
|
||||
|
||||
var w = db.storage.write(dest, db.getState(), format.serialize);
|
||||
return isPromise(w) ? w.then(function () {
|
||||
return value;
|
||||
}) : value;
|
||||
};
|
||||
|
||||
db.plant = function (state) {
|
||||
db[key] = state;
|
||||
return db;
|
||||
};
|
||||
|
||||
db.getState = function () {
|
||||
return db[key];
|
||||
};
|
||||
|
||||
db.setState = function (state) {
|
||||
db.plant(state);
|
||||
return db.write();
|
||||
};
|
||||
|
||||
return db.read();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init: init
|
||||
};
|
||||
|
||||
/***/ }),
|
||||
/* 1 */
|
||||
/***/ (function(module, exports) {
|
||||
|
||||
module.exports = _;
|
||||
|
||||
/***/ }),
|
||||
/* 2 */
|
||||
/***/ (function(module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
|
||||
/* global localStorage */
|
||||
|
||||
module.exports = {
|
||||
read: function browserRead(source) {
|
||||
var deserialize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : JSON.parse;
|
||||
|
||||
var data = localStorage.getItem(source);
|
||||
if (data) {
|
||||
return deserialize(data);
|
||||
} else {
|
||||
localStorage.setItem(source, '{}');
|
||||
return {};
|
||||
}
|
||||
},
|
||||
write: function browserWrite(dest, obj) {
|
||||
var serialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : JSON.stringify;
|
||||
|
||||
localStorage.setItem(dest, serialize(obj));
|
||||
}
|
||||
};
|
||||
|
||||
/***/ }),
|
||||
/* 3 */
|
||||
/***/ (function(module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
|
||||
module.exports = {
|
||||
read: function memoryRead() {
|
||||
return {};
|
||||
},
|
||||
write: function memoryWrite() {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
/***/ }),
|
||||
/* 4 */
|
||||
/***/ (function(module, exports) {
|
||||
|
||||
module.exports = isPromise;
|
||||
|
||||
function isPromise(obj) {
|
||||
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
|
||||
}
|
||||
|
||||
|
||||
/***/ }),
|
||||
/* 5 */
|
||||
/***/ (function(module, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
|
||||
var lodash = __webpack_require__(1);
|
||||
var common = __webpack_require__(0);
|
||||
|
||||
module.exports = function (source) {
|
||||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
|
||||
// Create a fresh copy of lodash
|
||||
var _ = lodash.runInContext();
|
||||
var db = _.chain({});
|
||||
|
||||
// Expose _ for mixins
|
||||
db._ = _;
|
||||
|
||||
// Add write function to lodash
|
||||
// Calls save before returning result
|
||||
_.prototype.write = _.wrap(_.prototype.value, function (func) {
|
||||
var dest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : source;
|
||||
|
||||
var funcRes = func.apply(this);
|
||||
return db.write(dest, funcRes);
|
||||
});
|
||||
|
||||
return common.init(db, '__wrapped__', source, opts);
|
||||
};
|
||||
|
||||
/***/ })
|
||||
/******/ ]);
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
/*! lowdb v0.15.5 */
|
||||
var low=function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=5)}([function(t,e,r){"use strict";var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(4),i=r(3),u=r(2),a=function(t,e,r){var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},c=a.storage,f=void 0===c?u:c,s=a.format,l=void 0===s?{}:s;return t.source=r,t.storage=n({},i,t.source&&f),t.read=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r,n=t.storage.read(e,l.deserialize);return o(n)?n.then(t.plant):t.plant(n)},t.write=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r,n=(arguments.length<=1?0:arguments.length-1)?arguments.length<=1?void 0:arguments[1]:t.getState(),i=t.storage.write(e,t.getState(),l.serialize);return o(i)?i.then(function(){return n}):n},t.plant=function(r){return t[e]=r,t},t.getState=function(){return t[e]},t.setState=function(e){return t.plant(e),t.write()},t.read()};t.exports={init:a}},function(t,e){t.exports=_},function(t,e,r){"use strict";t.exports={read:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:JSON.parse,r=localStorage.getItem(t);return r?e(r):(localStorage.setItem(t,"{}"),{})},write:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:JSON.stringify;localStorage.setItem(t,r(e))}}},function(t,e,r){"use strict";t.exports={read:function(){return{}},write:function(){return{}}}},function(t,e){function r(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}t.exports=r},function(t,e,r){"use strict";var n=r(1),o=r(0);t.exports=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.runInContext(),i=r.chain({});return i._=r,r.prototype.write=r.wrap(r.prototype.value,function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,n=e.apply(this);return i.write(r,n)}),o.init(i,"__wrapped__",t,e)}}]);
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
# Examples
|
||||
|
||||
## CLI
|
||||
|
||||
```js
|
||||
// cli.js
|
||||
const low = require('lowdb')
|
||||
const db = low('db.json')
|
||||
|
||||
db.defaults({ posts: [] })
|
||||
.write()
|
||||
|
||||
const result = db.get('posts')
|
||||
.push({ name: process.argv[2] })
|
||||
.write()
|
||||
|
||||
console.log(result)
|
||||
```
|
||||
|
||||
```sh
|
||||
$ node cli.js hello
|
||||
# [ { title: 'hello' } ]
|
||||
```
|
||||
|
||||
## Browser
|
||||
|
||||
```js
|
||||
import low from 'lowdb'
|
||||
const db = low('db')
|
||||
|
||||
db.defaults({ posts: [] })
|
||||
.write()
|
||||
|
||||
// Data is automatically saved to localStorage
|
||||
db.get('posts')
|
||||
.push({ title: 'lowdb' })
|
||||
.write()
|
||||
```
|
||||
|
||||
## Server
|
||||
|
||||
Please __note__ that if you're developing a local server and don't expect to get concurrent requests, it's often easier to use `file-sync` storage, which is the default.
|
||||
|
||||
But if you need to avoid blocking requests, you can do so by using `file-async` storage.
|
||||
|
||||
```js
|
||||
const express = require('express')
|
||||
const low = require('lowdb')
|
||||
const fileAsync = require('lowdb/lib/storages/file-async')
|
||||
|
||||
// Create server
|
||||
const app = express()
|
||||
|
||||
// Start database using file-async storage
|
||||
const db = low('db.json', {
|
||||
storage: fileAsync
|
||||
})
|
||||
|
||||
// Routes
|
||||
// GET /posts/:id
|
||||
app.get('/posts/:id', (req, res) => {
|
||||
const post = db.get('posts')
|
||||
.find({ id: req.params.id })
|
||||
.value()
|
||||
|
||||
res.send(post)
|
||||
})
|
||||
|
||||
// POST /posts
|
||||
app.post('/posts', (req, res) => {
|
||||
db.get('posts')
|
||||
.push(req.body)
|
||||
.last()
|
||||
.assign({ id: Date.now() })
|
||||
.write()
|
||||
.then(post => res.send(post))
|
||||
})
|
||||
|
||||
// Init
|
||||
db.defaults({ posts: [] })
|
||||
.write()
|
||||
.then(() => {
|
||||
app.listen(3000, () => console.log('Server is listening')
|
||||
})
|
||||
```
|
||||
|
||||
Using ES7 `async/await` and [Babel](https://babeljs.io/), you can simplify the previous `POST` example above like this:
|
||||
|
||||
```js
|
||||
app.post('/posts', async (req, res) => {
|
||||
const post = await db.get('posts')
|
||||
.push(req.body)
|
||||
.last()
|
||||
.assign({ id: Date.now() })
|
||||
.write()
|
||||
|
||||
res.send(post)
|
||||
})
|
||||
```
|
||||
|
||||
## In-memory
|
||||
|
||||
In this mode, no storage is used. Everything is done in memory.
|
||||
|
||||
You can still persist data but you'll have to do it yourself. Here's an example:
|
||||
|
||||
```js
|
||||
const fs = require('fs')
|
||||
const db = low()
|
||||
|
||||
db.defaults({ posts: [] })
|
||||
.write()
|
||||
|
||||
db.get('posts')
|
||||
.push({ title: 'lowdb' })
|
||||
.write()
|
||||
|
||||
// Manual writing
|
||||
fs.writeFileSync('db.json', JSON.stringify(db.getState()))
|
||||
```
|
||||
|
||||
In this case, it's recommended to create a custom storage.
|
||||
|
||||
## FP
|
||||
|
||||
This particular mode lets you use [lodash/fp](https://github.com/lodash/lodash/wiki/FP-Guide), [Ramda](https://github.com/ramda/ramda) or simple JavaScript functions with lowdb. If you're using Lowdb with a bundler like Webpack or Browserify it can help reducing the size of your bundle.js.
|
||||
|
||||
```js
|
||||
import low from 'lowdb/lib/fp'
|
||||
import concat from 'lodash/fp/concat'
|
||||
|
||||
const db = low()
|
||||
|
||||
// Get or set posts
|
||||
const posts = db('posts', [])
|
||||
|
||||
posts.write(
|
||||
concat({ title: 'lowdb is awesome' })
|
||||
)
|
||||
|
||||
const post = posts(
|
||||
find({ id: 1 })
|
||||
)
|
||||
```
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
||||
|
||||
var isPromise = require('is-promise');
|
||||
var memory = require('./storages/memory');
|
||||
var defaultStorage = require('./storages/file-sync');
|
||||
|
||||
var init = function init(db, key, source) {
|
||||
var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
|
||||
_ref$storage = _ref.storage,
|
||||
storage = _ref$storage === undefined ? defaultStorage : _ref$storage,
|
||||
_ref$format = _ref.format,
|
||||
format = _ref$format === undefined ? {} : _ref$format;
|
||||
|
||||
db.source = source;
|
||||
|
||||
// Set storage
|
||||
// In-memory only if no source is provided
|
||||
db.storage = _extends({}, memory, db.source && storage);
|
||||
|
||||
db.read = function () {
|
||||
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : source;
|
||||
|
||||
var r = db.storage.read(s, format.deserialize);
|
||||
|
||||
return isPromise(r) ? r.then(db.plant) : db.plant(r);
|
||||
};
|
||||
|
||||
db.write = function () {
|
||||
var dest = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : source;
|
||||
|
||||
var value = (arguments.length <= 1 ? 0 : arguments.length - 1) ? arguments.length <= 1 ? undefined : arguments[1] : db.getState();
|
||||
|
||||
var w = db.storage.write(dest, db.getState(), format.serialize);
|
||||
return isPromise(w) ? w.then(function () {
|
||||
return value;
|
||||
}) : value;
|
||||
};
|
||||
|
||||
db.plant = function (state) {
|
||||
db[key] = state;
|
||||
return db;
|
||||
};
|
||||
|
||||
db.getState = function () {
|
||||
return db[key];
|
||||
};
|
||||
|
||||
db.setState = function (state) {
|
||||
db.plant(state);
|
||||
return db.write();
|
||||
};
|
||||
|
||||
return db.read();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init: init
|
||||
};
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
var flow = require('lodash/fp/flow');
|
||||
var get = require('lodash/get');
|
||||
var set = require('lodash/set');
|
||||
var common = require('./common');
|
||||
|
||||
module.exports = function (source) {
|
||||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
|
||||
function db(path, defaultValue) {
|
||||
function getValue(funcs) {
|
||||
var result = get(db.getState(), path, defaultValue);
|
||||
return flow(funcs)(result);
|
||||
}
|
||||
|
||||
getValue.write = function () {
|
||||
var result = getValue.apply(undefined, arguments);
|
||||
set(db.getState(), path, result);
|
||||
return db.write(source, result);
|
||||
};
|
||||
|
||||
return getValue;
|
||||
}
|
||||
|
||||
return common.init(db, '__state__', source, opts);
|
||||
};
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
var lodash = require('lodash');
|
||||
var common = require('./common');
|
||||
|
||||
module.exports = function (source) {
|
||||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
|
||||
// Create a fresh copy of lodash
|
||||
var _ = lodash.runInContext();
|
||||
var db = _.chain({});
|
||||
|
||||
// Expose _ for mixins
|
||||
db._ = _;
|
||||
|
||||
// Add write function to lodash
|
||||
// Calls save before returning result
|
||||
_.prototype.write = _.wrap(_.prototype.value, function (func) {
|
||||
var dest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : source;
|
||||
|
||||
var funcRes = func.apply(this);
|
||||
return db.write(dest, funcRes);
|
||||
});
|
||||
|
||||
return common.init(db, '__wrapped__', source, opts);
|
||||
};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
|
||||
var common = require('./common');
|
||||
|
||||
module.exports = function (source) {
|
||||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
||||
|
||||
return common.init({}, '__state__', source, opts);
|
||||
};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
var jph = require('json-parse-helpfulerror');
|
||||
|
||||
module.exports = {
|
||||
parse: jph.parse,
|
||||
stringify: function stringify(obj) {
|
||||
return JSON.stringify(obj, null, 2);
|
||||
}
|
||||
};
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
/* global localStorage */
|
||||
|
||||
module.exports = {
|
||||
read: function browserRead(source) {
|
||||
var deserialize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : JSON.parse;
|
||||
|
||||
var data = localStorage.getItem(source);
|
||||
if (data) {
|
||||
return deserialize(data);
|
||||
} else {
|
||||
localStorage.setItem(source, '{}');
|
||||
return {};
|
||||
}
|
||||
},
|
||||
write: function browserWrite(dest, obj) {
|
||||
var serialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : JSON.stringify;
|
||||
|
||||
localStorage.setItem(dest, serialize(obj));
|
||||
}
|
||||
};
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
var steno = require('steno');
|
||||
|
||||
var _require = require('./_json'),
|
||||
stringify = _require.stringify;
|
||||
|
||||
module.exports = {
|
||||
read: require('./file-sync').read,
|
||||
write: function fileAsyncWrite(dest, obj) {
|
||||
var serialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringify;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var data = serialize(obj);
|
||||
|
||||
steno.writeFile(dest, data, function (err) {
|
||||
if (err) return reject(err);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('graceful-fs');
|
||||
|
||||
var _require = require('./_json'),
|
||||
parse = _require.parse,
|
||||
stringify = _require.stringify;
|
||||
|
||||
module.exports = {
|
||||
read: function fileSyncRead(source) {
|
||||
var deserialize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : parse;
|
||||
|
||||
if (fs.existsSync(source)) {
|
||||
// Read database
|
||||
var data = fs.readFileSync(source, 'utf-8').trim() || '{}';
|
||||
|
||||
try {
|
||||
return deserialize(data);
|
||||
} catch (e) {
|
||||
if (e instanceof SyntaxError) {
|
||||
e.message = 'Malformed JSON in file: ' + source + '\n' + e.message;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
} else {
|
||||
// Initialize empty database
|
||||
fs.writeFileSync(source, '{}');
|
||||
return {};
|
||||
}
|
||||
},
|
||||
write: function fileSyncWrite(dest, obj) {
|
||||
var serialize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringify;
|
||||
|
||||
var data = serialize(obj);
|
||||
fs.writeFileSync(dest, data);
|
||||
}
|
||||
};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
|
||||
module.exports = {
|
||||
read: function memoryRead() {
|
||||
return {};
|
||||
},
|
||||
write: function memoryWrite() {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"_from": "lowdb@^0.15.0",
|
||||
"_id": "lowdb@0.15.5",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha1-mt4QXfiqVzaS0SIWIrhUFPv0+pY=",
|
||||
"_location": "/lowdb",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "lowdb@^0.15.0",
|
||||
"name": "lowdb",
|
||||
"escapedName": "lowdb",
|
||||
"rawSpec": "^0.15.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^0.15.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/json-server"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/lowdb/-/lowdb-0.15.5.tgz",
|
||||
"_shasum": "9ade105df8aa573692d1221622b85414fbf4fa96",
|
||||
"_spec": "lowdb@^0.15.0",
|
||||
"_where": "D:\\izyim-mockapi\\node_modules\\json-server",
|
||||
"author": {
|
||||
"name": "Typicode",
|
||||
"email": "typicode@gmail.com"
|
||||
},
|
||||
"browser": {
|
||||
"./src/storages/file-sync.js": "./src/storages/browser.js",
|
||||
"./lib/storages/file-sync.js": "./lib/storages/browser.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/typicode/lowdb/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.1.3",
|
||||
"is-promise": "^2.1.0",
|
||||
"json-parse-helpfulerror": "^1.0.3",
|
||||
"lodash": "4",
|
||||
"steno": "^0.4.1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "JSON database for Node and the browser powered by lodash API",
|
||||
"devDependencies": {
|
||||
"babel-cli": "^6.2.0",
|
||||
"babel-eslint": "^7.0.0",
|
||||
"babel-loader": "^6.2.2",
|
||||
"babel-polyfill": "^6.9.1",
|
||||
"babel-preset-es2015": "^6.1.18",
|
||||
"babel-preset-stage-3": "^6.3.13",
|
||||
"babel-register": "^6.9.0",
|
||||
"husky": "^0.13.0",
|
||||
"ramda": "^0.23.0",
|
||||
"rimraf": "^2.5.4",
|
||||
"sinon": "^1.17.2",
|
||||
"standard": "^8.5.0",
|
||||
"tap-spec": "^4.1.1",
|
||||
"tape": "^4.2.2",
|
||||
"tempfile": "^1.1.1",
|
||||
"underscore-db": "^0.12.0",
|
||||
"webpack": "^2.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.12"
|
||||
},
|
||||
"homepage": "https://github.com/typicode/lowdb",
|
||||
"keywords": [
|
||||
"flat",
|
||||
"file",
|
||||
"local",
|
||||
"database",
|
||||
"storage",
|
||||
"JSON",
|
||||
"lo-dash",
|
||||
"lodash",
|
||||
"underscore",
|
||||
"localStorage",
|
||||
"embed",
|
||||
"embeddable"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "./lib/main.js",
|
||||
"name": "lowdb",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/typicode/lowdb.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:lib && npm run build:dist",
|
||||
"build:dist": "rimraf dist && webpack && webpack -p",
|
||||
"build:lib": "rimraf lib && babel src --out-dir lib",
|
||||
"fix": "standard --fix",
|
||||
"precommit": "npm test",
|
||||
"prepublish": "npm run build",
|
||||
"tape": "tape -r babel-register -r babel-polyfill test/*.js | tap-spec",
|
||||
"test": "npm run tape && standard"
|
||||
},
|
||||
"standard": {
|
||||
"parser": "babel-eslint"
|
||||
},
|
||||
"version": "0.15.5"
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
var path = require('path')
|
||||
var webpack = require('webpack')
|
||||
var pkg = require('./package.json')
|
||||
var banner = 'lowdb v' + pkg.version
|
||||
|
||||
module.exports = {
|
||||
entry: './src/main.js',
|
||||
output: {
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
filename: process.argv.indexOf('-p') !== -1
|
||||
? 'lowdb.min.js'
|
||||
: 'lowdb.js',
|
||||
library: 'low'
|
||||
},
|
||||
externals: {
|
||||
lodash: '_'
|
||||
},
|
||||
plugins: [
|
||||
new webpack.BannerPlugin(banner)
|
||||
],
|
||||
module: {
|
||||
loaders: [
|
||||
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user