Skip to content

Commit fd84dec

Browse files
committed
First commit
1 parent cfe274c commit fd84dec

File tree

3 files changed

+233
-1
lines changed

3 files changed

+233
-1
lines changed

README.md

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,53 @@
11
# database-js-json
2-
Database-js driver for JSON files
2+
3+
A [database-js](https://github.com/mlaanderson/database-js) driver for JSON files.
4+
5+
## About
6+
7+
This is a wrapper around the [jl-sql-api](https://github.com/avz/node-jl-sql-api), intended to be used with [database-js](https://github.com/mlaanderson/database-js) for handling JSON files.
8+
9+
## Install
10+
11+
```shell
12+
npm install database-js-json
13+
```
14+
15+
## Basic Usage
16+
17+
```javascript
18+
var Connection = require( 'database-js2' ).Connection;
19+
20+
(async () => {
21+
const connection = new Database( 'json:///test.json' );
22+
23+
try {
24+
let statement = await connection.prepareStatement("SELECT * WHERE user_name = ?");
25+
let rows = await statement.query('not_so_secret_user');
26+
console.log(rows);
27+
} catch (error) {
28+
console.log(error);
29+
} finally {
30+
await connection.close();
31+
}
32+
} )();
33+
```
34+
35+
### Options
36+
37+
Options from [jl-sql-api](https://github.com/avz/node-jl-sql-api) can be passed as arguments to the database connection, in the format of a URL.
38+
39+
Example: `{ tmpDir: "/path/to/dir" }`
40+
```javascript
41+
const connection = new Database( 'json:///test.json?tmpDir=path/to/dir' );
42+
```
43+
44+
When an option that belongs to a group is informed, it must have a dot.
45+
46+
Example: `{ tmpDir: "/path/to/dir", sortOptions: { inMemoryBufferSize: 32000 } }`
47+
```javascript
48+
const connection = new Database( 'json:///test.json?tmpDir=path/to/dir&sortOptions.inMemoryBufferSize=32000' );
49+
```
50+
51+
## License
52+
53+
[MIT](https://github.com/thiagodp/database-js-json/blob/master/LICENSE) (c) [thiagodp](https://github.com/thiagodp)

index.js

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
var JlSqlApi = require( 'jl-sql-api' );
2+
var fs = require( 'fs' );
3+
4+
/**
5+
* Database-js driver for JSON files.
6+
*
7+
* @see https://github.com/mlaanderson/database-js
8+
*/
9+
class JsonDriver {
10+
11+
/**
12+
* Constructor
13+
*
14+
* @param {string} filename File name
15+
* @param {object} options Options. Defaults to { charset: 'utf-8' }.
16+
*
17+
* @see https://github.com/avz/node-jl-sql-api#options-object for more options.
18+
*/
19+
constructor( filename, options ) {
20+
21+
this._api = new JlSqlApi();
22+
23+
this._filename = filename;
24+
25+
this._options = Object.assign( {
26+
charset: 'utf-8'
27+
}, options );
28+
29+
this._data = null;
30+
}
31+
32+
/**
33+
* Loads the file and returns a promise to its content.
34+
*
35+
* @returns {Promise}
36+
*/
37+
_loadFile() {
38+
return new Promise( function ( resolve, reject ) {
39+
fs.readFile( this._filename, this._options.charset, function ( err, data ) {
40+
if ( err ) {
41+
return reject( err );
42+
}
43+
try {
44+
return resolve( JSON.parse( data ) );
45+
} catch ( e ) {
46+
return reject( e );
47+
}
48+
} );
49+
} );
50+
}
51+
52+
/**
53+
* Saves the file and returns a promise with no data.
54+
*
55+
* @returns {Promise}
56+
*/
57+
_saveFile() {
58+
return new Promise( function ( resolve, reject ) {
59+
fs.writeFile( this._filename, this._data || [], this._options.charset, function ( err ) {
60+
if ( err ) {
61+
return reject( err );
62+
}
63+
return resolve();
64+
} );
65+
} );
66+
}
67+
68+
/**
69+
* Returns a promise to the file content.
70+
*
71+
* @param {boolean} reloadFile Whether is desired to reload the file. Defaults to false.
72+
* @returns {Promise}
73+
*/
74+
data( reloadFile ) {
75+
if ( this._data && ! reloadFile ) {
76+
return Promise.resolve( this._data );
77+
}
78+
return this._loadFile().then( function ( data ) {
79+
this._data = data;
80+
return data;
81+
} );
82+
}
83+
84+
/**
85+
* Executes the given query and returns a promise to the resulting data.
86+
*
87+
* @param {string} sql Query to execute.
88+
* @returns {Promise}
89+
*/
90+
query( sql ) {
91+
return new Promise( function( resolve, reject ) {
92+
93+
var queryData = function( data ) {
94+
api.query( sql )
95+
.fromArrayOfObjects( Array.isArray( data ) ? data : [ data ] )
96+
.toArrayOfObjects( function( rows ) {
97+
resolve( rows );
98+
} );
99+
};
100+
101+
this.data()
102+
.then( queryData )
103+
.catch( function ( err ) { reject( err ); } );
104+
} );
105+
}
106+
107+
/**
108+
* Executes the given command and returns a promise with the resulting data.
109+
* The file is saved after the command execution, whether successful.
110+
*
111+
* @param {string} sql Command to execute.
112+
* @returns {Promise}
113+
*/
114+
execute( sql ) {
115+
116+
return new Promise( function( resolve, reject ) {
117+
118+
this.query( sql )
119+
.then( function keepResults( rows ) {
120+
this._data = rows; // Keep the last content
121+
return rows;
122+
} )
123+
.then( function saveToFile( rows ) {
124+
return this._saveFile()
125+
.then( function ( data ) { resolve( data ); } )
126+
.catch( function ( err ) { reject( err ); } );
127+
} )
128+
.catch( function ( err ) { reject( err ); } );
129+
} );
130+
}
131+
132+
}
133+
134+
module.exports = {
135+
open: function( connection ) {
136+
137+
var options = {};
138+
if ( connection.Parameters ) {
139+
connection.Parameters.split( '&' ).map( function ( s ) {
140+
141+
var separated = s.split( '=' );
142+
var key = separated[ 0 ];
143+
var val = separated[ 1 ];
144+
var subKey = null;
145+
146+
// e.g. "sortOptions.bufferSize"
147+
if ( key.indexOf( '.' ) >= 0 ) {
148+
var sub = key.split( '.' );
149+
key = sub[ 0 ];
150+
subKey = sub[ 1 ];
151+
}
152+
153+
if ( ! subKey ) {
154+
options[ key ] = val;
155+
} else {
156+
if ( ! options[ key ] ) {
157+
options[ key ] = {};
158+
}
159+
options[ key ][ subKey ] = val;
160+
}
161+
});
162+
}
163+
164+
return new JsonDriver( connection.Database, options );
165+
}
166+
};

package.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"name": "database-js-json",
3+
"version": "0.1.0",
4+
"description": "Database-js driver for JSON files",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": ["database-js","json"],
10+
"author": "Thiago Delgado Pinto",
11+
"license": "MIT",
12+
"dependencies": {
13+
"jl-sql-api": "^2.8.1"
14+
}
15+
}

0 commit comments

Comments
 (0)