Skip to content

Instantly share code, notes, and snippets.

@k1r0s
Created August 26, 2018 22:37
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/6e2bdebd5babf56e7f26e8ee41c627e1 to your computer and use it in GitHub Desktop.
Save k1r0s/6e2bdebd5babf56e7f26e8ee41c627e1 to your computer and use it in GitHub Desktop.
import { AbstractResource } from "@ritley/core";
import UserModel from "../models/user.model";
import ParseReqBody from "../decorators/req-body-json.decorator";
import ValidateSession from "../decorators/validate-session.decorator";
import {
ReqTransformQuery,
Dependency,
Default,
Catch,
InternalServerError,
BadRequest,
Conflict,
Created,
Forbidden,
Ok
} from "@ritley/decorators";
@Dependency("userModel", UserModel)
export default class UserResource extends AbstractResource {
constructor(_database) {
super("/users");
}
@Default(Created)
@ParseReqBody
async post(req, res, payload) {
await this.validate(payload, res);
await this.isUnique(payload, res);
return await this.create(payload, res);
}
@Default(Ok)
@ReqTransformQuery
@ValidateSession
@ParseReqBody
async put(req, res, session, payload) {
await this.hasPermission(req, res, session);
return await this.updateUser(req, res, payload);
}
@Default(Ok)
@ValidateSession
async get(req, res, session) {
return this.readUsers(req, res);
}
@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() {
return this.userModel.searchBy();
}
@Catch(Forbidden, "you don't have permissions to perform this action")
hasPermission(req, res, session) {
return this.userModel.isAllowedToEdit(req.query.uid, session.userUid);
}
@Catch(InternalServerError, "there was an error updating the user")
updateUser(req, res, payload) {
const requestedUserUid = req.query.uid;
return this.userModel.update(requestedUserUid, payload);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment