Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Exceptionless Blog Post - User Association
import { Exceptionless } from "@exceptionless/node";
import express from "express";
const router = express.Router();
await Exceptionless.startup("YOUR API KEY");
const users = [
{
key: "123",
user: {
name: "Justin Hunter",
email: "justin@email.com",
userId: "76a62f17-e177-4cc5-b2aa-49a4d59c99a5"
}
},
{
key: "456",
user: {
name: "Sarah Sanders",
email: "sarah@email.com",
userId: "6840f55b-6694-49b9-b609-40fbcbf155fe"
}
}
]
const authentication = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
const keyFound = users.find(u => u.key === apiKey);
if(!keyFound) {
return res.status(401).send("Unauthorized");
}
res.locals.user = keyFound.user;
next();
}
const validBody = (body) => {
if(!body.name || !body.email || !body.userId) {
return false;
}
return true;
}
/* GET users listing. */
router.get('/', authentication, function(req, res, next) {
const mappedUsers = users.map((u) => {return {
name: u.user.name,
email: u.user.email,
userId: u.user.userId
}});
res.json(mappedUsers);
});
/* POST new user */
router.post('/', authentication, async function(req, res, next) {
try {
if(!validBody(req.body)) {
throw new Error("No user object provided");
}
users.push({
apiKey: null,
user: req.body
});
res.json(req.body);
} catch (error) {
await Exceptionless.createException(error).setUserIdentity(res.locals.user).submit();
res.status(400).send(error.message);
}
})
export default router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment