Install nedb-promises
nedb-promises
is a wrapper around NEDB. I suggest using this over Nedb directly. Sooner or later, you’d need to wait for your data to arrive.
$ yarn add nedb-promises
Create a database factory
You can choose to have just one database file for your entire app, or you can choose to have one file per domain entity. But the location of those files can cause a problem after you have packaged the app.
Electron provides a getAppPath
helper. We use userData
to store the database files in a packaged app, and ./data/
in development.
If you are using my Glutten free react electron structure, create a file named db.js
in main/src
folder. If not, place this file where you see fit. It will be used to load data entities.
// main/src/db.js
const {app} = require('electron');
const Datastore = require('nedb-promises');
const dbFactory = (fileName) => Datastore.create({
filename: `${process.env.NODE_ENV === 'dev' ? '.' : app.getAppPath('userData')}/data/${fileName}`,
timestampData: true,
autoload: true
});
I also pass some nifty defaults like autoload and auto timestamping.
Setup environment
Now we need to inform electron about our environment. We can do so by modifying package.json.
"scripts": {
"start": "NODE_ENV=dev electron src",
"build": "NODE_ENV=prod electron-builder",
},
I usestart
command in my development env and build to create the package. If you use different commands, adjust accordingly.
Setup domains objects
Suppose you need to persist two domain objects: posts and tags. In this example, I’m gonna persist posts in posts.db
file and tags in tags.db
file. (You can use a single file.)
We do so by extending the
// db.js
// requires
// const dbFactory = ...
const db = {
tags: dbFactory('tags.db'),
posts: dbFactory('posts.db')
};
module.exports = db;
Query records
Now your domain objects are accessible as db.tags
and db.posts
. Follow the NEDB API as usual.
const db = require('db')
const createTag = async (label) => {
const tag = await db.tags.insert({label})
return tag
}
const getTags = async () => {
const proxies = await db.tags.find({})
return {proxies}
}