const joi = require('joi'); const { ObjectID } = require('mongodb'); const { clientError } = require('server/modules/client-error'); const COLLECTION_USERS = 'users'; function getObjectId(id) { if (process.env.NODE_ENV === 'test') { return id; } return new ObjectID(id); } async function insertUser(db, info) { const { error, value } = joi.validate(info, { name: joi.string().required(), email: joi.string() .email() .required() }); if (error) { throw clientError(error); } const users = await db.collection(COLLECTION_USERS); const result = await users.insert(value); try { const { _id, ...userResult } = result.ops[0]; return { id: String(_id), ...userResult }; } catch (err) { return value; } } async function modifyUser(db, id, info) { const { error, value } = joi.validate(info, { name: joi.string(), email: joi.string() .email() }); if (error) { throw clientError(error); } const users = await db.collection(COLLECTION_USERS); const _id = getObjectId(id); await users.updateOne({ _id }, { $set: value }, { upsert: false, multi: false }); } async function deleteUser(db, id) { const users = await db.collection(COLLECTION_USERS); await users.deleteOne({ _id: getObjectId(id) }); } async function getUsers(db) { const users = await db.collection(COLLECTION_USERS); const rows = await users.find({}) .toArray(); return rows.map(({ _id, ...rest }) => ({ id: String(_id), ...rest })); } module.exports = { insertUser, modifyUser, deleteUser, getUsers, COLLECTION_USERS };