Last active
August 25, 2018 16:07
-
-
Save k1r0s/4d3e930e095d8f8dd96eb48ca6b2c625 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { AbstractResource } from "@ritley/core"; | |
| import DataService from "../services/database.service"; | |
| import UserModel from "../models/user.model"; | |
| import { Dependency, ReqTransformBodyAsync } from "@ritley/decorators"; | |
| @Dependency("userModel", UserModel) | |
| export default class UserResource extends AbstractResource { | |
| constructor(_database) { | |
| super("/users"); | |
| } | |
| @ReqTransformBodyAsync | |
| async post(req, res) { | |
| const body = await req.body; | |
| const payload = this.parseBody(body, res); | |
| await this.validate(payload, res); | |
| await this.isUnique(payload, res); | |
| const user = await this.create(payload, res); | |
| res.statusCode = 200; | |
| res.end(JSON.stringify(user)); | |
| } | |
| parseBody(body, res) { | |
| try { | |
| return body.toJSON(); | |
| } catch (e) { | |
| res.statusCode = 400; | |
| res.end("payload isn't well formed"); | |
| } | |
| } | |
| validate(payload, res) { | |
| return this.userModel.validate(payload).catch(() => { | |
| res.statusCode = 400; | |
| res.end("missing fields, required: [name, mail, pass]"); | |
| }) | |
| } | |
| isUnique(payload, res) { | |
| return this.userModel.isUnique(payload).catch(() => { | |
| res.statusCode = 409; | |
| res.end("mail is already taken, try another one"); | |
| }) | |
| } | |
| create(payload, res) { | |
| return this.userModel.create(payload).catch(() => { | |
| res.statusCode = 500; | |
| res.end("there was an error creating your user, try again"); | |
| }) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment