Skip to content

Instantly share code, notes, and snippets.

@k1r0s
Created August 26, 2018 14:03
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 k1r0s/815bd40383953dbcfc9dbbf1d8b92a91 to your computer and use it in GitHub Desktop.
Save k1r0s/815bd40383953dbcfc9dbbf1d8b92a91 to your computer and use it in GitHub Desktop.
import { AbstractResource } from "@ritley/core";
import DataService from "../services/database.service";
import UserModel from "../models/user.model";
import SessionModel from "../models/session.model";
import {
Dependency,
ReqTransformBodyAsync,
Default,
Catch,
InternalServerError,
BadRequest,
Conflict,
Created,
Ok,
ReqTransformQuery,
Unauthorized
} from "@ritley/decorators";
@Dependency("userModel", UserModel)
@Dependency("sessionModel", SessionModel)
export default class UserResource extends AbstractResource {
constructor(_database) {
super("/users");
}
@Default(Created)
@ReqTransformBodyAsync
async post(req, res) {
const payload = await this.parseBody(req, res);
await this.validate(payload, res);
await this.isUnique(payload, res);
return await this.create(payload, res);
}
@Default(Ok)
@ReqTransformQuery
async get(req, res) {
const session = await this.getSession(req, res);
return this.readUsers(req, res, session);
}
@Catch(BadRequest, "payload isn't well formed")
parseBody(req) {
return req.body.then(body => body.toJSON());
}
@Catch(BadRequest, "missing fields, required: [name, mail, pass]")
validate(payload) {
return this.userModel.validate(payload);
}
@Catch(Conflict, "mail is already taken, try another one")
isUnique(payload) {
return this.userModel.isUnique(payload);
}
@Catch(InternalServerError, "there was an error creating your user, try again")
create(payload) {
return this.userModel.create(payload);
}
@Catch(InternalServerError, "there was an error trying to retrieve user list")
readUsers(req, res, session) {
const predicate = req.query.filter && this.query.getFilter(req.query.filter);
return this.userModel.searchBy(predicate);
}
async getSession(req, res) {
const session = await this.sessionExists(req, res);
return this.isSessionValid(session);
}
@Catch(Unauthorized, "you need to create a session to perform this action")
sessionExists(req) {
const uid = req.headers["x-session"];
return this.sessionModel.sessionExists({ uid });
}
@Catch(Unauthorized, "your session has expired")
isSessionValid(session) {
return this.sessionModel.revalidate(session);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment