1
0
mirror of https://github.com/verdaccio/verdaccio.git synced 2024-11-13 03:35:52 +01:00
verdaccio/lib/storage/local/local-data.js

73 lines
1.3 KiB
JavaScript
Raw Normal View History

'use strict';
2017-04-17 16:10:21 +02:00
const fs = require('fs');
2017-04-17 16:10:21 +02:00
const Path = require('path');
/**
* Handle local database.
* FUTURE: must be a plugin.
*/
2017-04-17 16:10:21 +02:00
class LocalData {
/**
* Load an parse the local json database.
* @param {*} path the database path
*/
2017-04-17 16:10:21 +02:00
constructor(path) {
this.path = path;
2017-04-17 16:10:21 +02:00
try {
this.data = JSON.parse(fs.readFileSync(this.path, 'utf8'));
2017-04-17 16:10:21 +02:00
} catch(_) {
this.data = {list: []};
2017-04-17 16:10:21 +02:00
}
}
/**
* Add a new element.
* @param {*} name
*/
2017-04-17 16:10:21 +02:00
add(name) {
if (this.data.list.indexOf(name) === -1) {
this.data.list.push(name);
this.sync();
2017-04-17 16:10:21 +02:00
}
}
/**
* Remove an element from the database.
* @param {*} name
*/
2017-04-17 16:10:21 +02:00
remove(name) {
const i = this.data.list.indexOf(name);
2017-04-17 16:10:21 +02:00
if (i !== -1) {
this.data.list.splice(i, 1);
2017-04-17 16:10:21 +02:00
}
this.sync();
}
/**
* Return all database elements.
* @return {Array}
*/
2017-04-17 16:10:21 +02:00
get() {
return this.data.list;
2017-04-17 16:10:21 +02:00
}
/**
* Syncronize {create} database whether does not exist.
*/
2017-04-17 16:10:21 +02:00
sync() {
// Uses sync to prevent ugly race condition
try {
require('mkdirp').sync(Path.dirname(this.path));
} catch(err) {
// perhaps a logger instance?
/* eslint no-empty:off */
}
fs.writeFileSync(this.path, JSON.stringify(this.data));
2017-04-17 16:10:21 +02:00
}
}
2017-04-17 16:10:21 +02:00
module.exports = LocalData;