Skip to content

Instantly share code, notes, and snippets.

@billinghamj
Created March 30, 2016 08:54
Show Gist options
  • Save billinghamj/2fdfc0425af1d0613392167413633b27 to your computer and use it in GitHub Desktop.
Save billinghamj/2fdfc0425af1d0613392167413633b27 to your computer and use it in GitHub Desktop.
Light MongoDB Abstraction
import log from 'cuvva-log';
import {MongoClient, ObjectID} from 'mongodb';
export default class Storage {
static async create(url) {
// for this particular service, majority is worth having
// if copying, evaluate your write concern needs properly
const db = await MongoClient.connect(url, {
db: { w: 'majority' },
});
log.info('database_connected');
return new Storage(db);
}
constructor(db) {
this.db = db;
this.users = new Model(db.collection('users'));
this.notes = new Model(db.collection('notes'));
this.createIndexes().catch(function (error) {
log.error('index_creation_failed', [error]);
});
}
async createIndexes() {
await Promise.all([
this.users.index(['createdAt', 'updatedAt']),
this.users.index(['state.title', 'state.sex', 'state.birthDate'], { sparse: true }),
this.users.index(['state.emailAddress', 'state.mobilePhone', 'state.facebookId'], { unique: true, sparse: true }),
this.notes.index(['userId', 'createdAt']),
]);
}
}
class Model {
constructor(collection) {
this.collection = collection;
}
async index(keys, options) {
const specs = keys.map(k => {
const spec = {};
spec[k] = 1;
return spec;
});
await Promise.all(specs.map(s => this.collection.createIndex(s, options)));
}
async create(object) {
const result = await this.collection.insertOne(object);
return result.ops[0];
}
async retrieve(id) {
return await this.findOne({ _id: ObjectID(id) });
}
async update(id, update) {
const query = { _id: ObjectID(id) };
const options = { returnOriginal: false };
const result = await this.collection.findOneAndUpdate(query, update, options);
return result.value;
}
async delete(id) {
await this.collection.deleteOne({ _id: ObjectID(id) });
}
async findOne(query) {
const object = await this.collection.findOne(query);
if (!object)
throw log.info('not_found');
return object;
}
async findMany(query) {
return await this.collection.find(query).toArray();
}
async count(query) {
return await this.collection.count(query);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment