Skip to content

Instantly share code, notes, and snippets.

@k1r0s
Created August 24, 2018 11:46
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/e1ac093b2e37b871d6a6b9f5472b3c9a to your computer and use it in GitHub Desktop.
Save k1r0s/e1ac093b2e37b871d6a6b9f5472b3c9a 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 {
Dependency,
ReqTransformBodyAsync,
Default,
Catch,
InternalServerError,
BadRequest,
Conflict,
Created
} from "@ritley/decorators";
@Dependency("userModel", UserModel)
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);
}
@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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment