Table of Content
Express session
var app = express();
var session = require("express-session");
app.set("trust proxy", 1); // trust first proxy
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: { secure: true }
})
);
Max age
- https://www.npmjs.com/package/express-session#cookiemaxage
after 1000ms, session will be deleted.
cookie: { secure: true, maxAge: 1000 }
Error Handling
Promise.resolve()
.then(() => {})
.then(results => {
// throw new Error('duplicate : userId'); // this way is for stack trace.(development)
return Promise.reject("duplicate"); // this way is for business logic(notify to client)
})
.catch(err => {
if (err === "duplicate") return jsonSender.sendDuplicate(res, "duplicate");
next(err);
});
Compare code
Promise.resolve()
.then(() => {
// Find userId already exists.
const promises = [];
const query = { userId: doc.userId };
promises.push(StagingUser.findOne(query));
promises.push(User.findOne(query));
return Promise.all(promises);
})
.then((results) => {
if (!(results[0] === null && results[1] === null)) return Promise.reject({ localError: true, localErrorMsg: 'DUPLICATE_USER_ID' });
return;
})
.then(() => {
// Find mobile number already exists.
const promises = [];
const query = { mobileNumber: doc.mobileNumber };
promises.push(StagingUser.findOne(query));
promises.push(User.findOne(query));
return Promise.all(promises);
})
.then((results) => {
if (!(results[0] === null && results[1] === null)) return Promise.reject({ localError: true, localErrorMsg: 'DUPLICATE_MOBILE_NUMBER' });
return;
})
.then(() => {
const stagingUser = new StagingUser(doc);
return stagingUser.save();
})
.then((dbRes) => {
jsonSender.sendSuccess(res, 'Staging user signup success');
})
.catch((err) => {
if (err.localError) return jsonSender.sendDuplicate(res, err.localErrorMsg);
next(err);
});
};
Promise.resolve()
.then(() => {
// Find userId already exists.
const promises = [];
const query = { userId: doc.userId };
promises.push(StagingUser.findOne(query));
promises.push(User.findOne(query));
return Promise.all(promises).then((results) => {
if (!(results[0] === null && results[1] === null)) return Promise.reject({ localError: true, localErrorMsg: 'DUPLICATE_USER_ID' });
return;
});
})
.then(() => {
// Find mobile number already exists.
const promises = [];
const query = { mobileNumber: doc.mobileNumber };
promises.push(StagingUser.findOne(query));
promises.push(User.findOne(query));
return Promise.all(promises).then((results) => {
if (!(results[0] === null && results[1] === null)) return Promise.reject({ localError: true, localErrorMsg: 'DUPLICATE_MOBILE_NUMBER' });
return;
});
})
.then(() => {
const stagingUser = new StagingUser(doc);
return stagingUser.save();
})
.then((dbRes) => {
jsonSender.sendSuccess(res, 'Staging user signup success');
})
.catch((err) => {
if (err.localError) return jsonSender.sendDuplicate(res, err.localErrorMsg);
next(err);
});
};
Today I Learned