Skip to content

Instantly share code, notes, and snippets.

@ianldgs
Last active February 24, 2020 14:29
Show Gist options
  • Save ianldgs/f9082720e504875bc990ca22e5c2b17e to your computer and use it in GitHub Desktop.
Save ianldgs/f9082720e504875bc990ca22e5c2b17e to your computer and use it in GitHub Desktop.
NodeJS routing experiment
export default function UserRoutes({ db, jwt }) {
const Validation = ctx => ({
name: [required(), minLength(2), maxLength(255)],
email: [required(!ctx.body.phone), email(), uniqueUserEmail(db)],
phone: [required(!ctx.body.email), phone(), uniqueUserPhone(db)],
document: [
required(),
async doc => doc.match(/\d+/) || ValidationErrors.invalid_document
]
});
return {
"*": {
path: "/users",
async auth(ctx, next) {
await jwt.is(ctx, "user");
next();
},
catch(ctx, error, next) {
if (error instanceof UnauthorizedError) {
ctx.status = 401;
return {
error: {
code: "unauthorized"
}
};
}
if (error instanceof ForbiddenError) {
ctx.status = 403;
return {
error: {
code: "forbidden"
}
};
}
if (error instanceof ValidationError) {
ctx.status = 400;
return {
error: {
code: "validation",
fields: error.fields
}
};
}
if (
error instanceof ModelNotFoundError ||
error instanceof NoRowsAffectedError
) {
ctx.status = 404;
return {
error: {
code: "not_found"
}
};
}
next(error);
}
},
"/": {
post: {
async auth(ctx, next) {
await jwt.is(ctx, "admin");
next();
},
async validate(ctx, next) {
await validator(ctx, Validation(ctx));
next();
},
async handle(ctx) {
const user = await db.users.insert(ctx.body);
ctx.status = 201;
return user;
}
},
async get(ctx) {
return db.users.findAll(ctx.query || {});
}
},
"/:id": {
async get(ctx) {
return db.users.findOneOrFail({ id: ctx.params.id });
},
put: {
async auth(ctx, next) {
await jwt.is(ctx, "admin");
next();
},
async validate(ctx, next) {
await validator(ctx, {
...Validation(ctx),
id: [readOnly()],
document: [readOnly()]
});
next();
},
async handle(ctx) {
const user = await db.users.updateOneOrFail(ctx.params.id, ctx.body);
return user;
}
},
delete: {
async auth(ctx, next) {
await jwt.is(ctx, "admin");
next();
},
async handle(ctx) {
await db.users.deleteOneOrFail({ id: ctx.params.id });
ctx.status = 204;
}
},
async patch(ctx) {
ctx.status = 405;
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment