Skip to content

Instantly share code, notes, and snippets.

@k1r0s
Created August 26, 2018 12:30
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/e3d3fd468b8bf79247201e89c9a9dbc5 to your computer and use it in GitHub Desktop.
Save k1r0s/e3d3fd468b8bf79247201e89c9a9dbc5 to your computer and use it in GitHub Desktop.
import { AbstractResource } from "@ritley/core";
import SessionModel from "../models/session.model";
import {
Default,
Catch,
MethodNotAllowed,
InternalServerError,
Created,
Unauthorized,
BadRequest,
Dependency,
ReqTransformBodyAsync
} from "@ritley/decorators";
@Dependency("sessionModel", SessionModel)
export default class SessionResource extends AbstractResource {
@Default(MethodNotAllowed) get() {}
@Default(MethodNotAllowed) put() {}
@Default(MethodNotAllowed) delete() {}
static URI = "/sessions";
constructor() {
super(SessionResource.URI);
}
@Default(Created)
@ReqTransformBodyAsync
async post(req, res) {
const payload = await this.parseBody(req, res);
const user = await this.getUserUsingCredentials(payload, res);
return await this.login(user, res);
}
@Catch(BadRequest, "payload isn't well formed")
parseBody(req) {
return req.body.then(body => body.toJSON());
}
@Catch(InternalServerError, "there was an error creating the session")
login(user) {
return this.sessionModel.upsertSession(user);
}
@Catch(Unauthorized, "your credentials are invalid")
getUserUsingCredentials(payload) {
return this.sessionModel.validateCredentials(payload);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment