Last active
December 23, 2020 22:53
-
-
Save fernandocamargo/5d1ca18797f8ec26a5223e8d73c585ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const LOCAL = { email: "njr@gmail.com", expiredPassword: true }; | |
const DB = { | |
preferences: { optIn: false }, | |
notifications: { duplicated: true, something: true, fake: false }, | |
bills: [1] | |
}; | |
const response = (type, res, params) => | |
console.log(JSON.stringify({ response: { type, res, params } }, null, 2)); | |
const userRepo = { | |
getByEmail: () => Promise.resolve(DB) | |
}; | |
const getUserBy = (email) => | |
userRepo | |
.getByEmail(email) | |
.then((user) => user || Promise.reject(Error("USER_NOT_FOUND"))) | |
.catch((error) => | |
Promise.reject(Error(error?.message || "ERROR_FETCHING_USERS")) | |
); | |
const getNotifications = (req, res) => { | |
const { params } = req; | |
const { | |
locals: { | |
user: { email, expiredPassword } | |
} | |
} = res; | |
const category = params?.category?.split(","); | |
const extract = ({ notifications, preferences, bills }) => { | |
const categories = Object.assign(notifications, { | |
overdue: !!bills.length, | |
marketing: preferences.optIn === "subscribed", | |
security: !!expiredPassword | |
}); | |
const select = (stack, [name, status]) => { | |
const skip = !status || (category && !category.includes(name)); | |
return skip ? stack : stack.concat({ category: name }); | |
}; | |
return Object.entries(categories).reduce(select, []); | |
}; | |
return getUserBy(email) | |
.then((user) => | |
response("SUCCESS_GENERIC", res, { notifications: extract(user) }) | |
) | |
.catch(({ message }) => response("ERROR_GENERIC", res, { error: message })); | |
}; | |
getNotifications( | |
{ params: { category: "security,overdue,fake" } }, | |
{ locals: { user: LOCAL } } | |
).then((notifications) => console.log({ notifications })); | |
// api.com/notifications => all | |
// api.com/notifications/overdue => [{ category: 'overdue' }] | |
// api.com/notifications/overdue,security => [ | |
// { category: 'overdue' }, { category: 'security' } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment