Skip to content

Instantly share code, notes, and snippets.

@luchoching
Created April 6, 2017 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luchoching/6677db76c29490cec9dfc8ae56e6cb49 to your computer and use it in GitHub Desktop.
Save luchoching/6677db76c29490cec9dfc8ae56e6cb49 to your computer and use it in GitHub Desktop.
use Async lib
const async = require('async');
const bcrypt = require('bcrypt');
const MongoClient = require('mongodb').MongoClient;
const NAME = 'mockuser';
const PWD = 'mockpwd';
const NUM = 5;
const URL = 'mongodb://localhost:27017/myApp';
const USERS = 'users';
const FOLDERS = 'folders';
function mockNames(name, num = 3) {
let count = 1;
return Array(num).fill(NAME).map(name => (`${name}-${count++}`));
}
function salt(cb) {
bcrypt.genSalt(2, (err, salt) => {
if(err) return cb(err);
cb(null, salt);
});
}
function hash(salt, cb) {
bcrypt.hash(PWD, salt, (err, hash)=> {
if(err) return cb(err);
cb(null, hash);
});
}
function connMongo(hash, cb) {
MongoClient.connect(URL, (err, db) => {
if(err) return cb(err);
cb(null, hash, db);
});
}
function addUsers(hash, db, cb) {
console.log('insert users to DB');
const names = mockNames(NAME, NUM);
const users = names
.map(name => ({
name,
pwd: hash
}));
db.collection(USERS)
.insertMany(users, (err, result) => {
if(err) return cb(err);
cb(null, db, names, result);
});
}
function addRootFolder(db, names, addUsersResult, cb) {
// {"owner" : "mockUser", "dir-1" : { "name" : "暫存區", "childs" : [] }
const rootFolders = names.map(name => ({
owner: name,
'dir-1': {
name: '暫存區',
childs: []
}
}));
db.collection(FOLDERS)
.insertMany(rootFolders, (err, addFolderResult) => {
if (err) return cb(err);
cb(null, db, addUsersResult, addFolderResult);
});
}
async.waterfall([
salt,
hash,
connMongo,
addUsers,
addRootFolder
], (err, db, addUsersResult, addFolderResult) => {
if (err) console.log(err);
else {
db.close();
console.log(addUsersResult);
console.log(addFolderResult);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment