Created
August 26, 2018 12:30
-
-
Save k1r0s/e3d3fd468b8bf79247201e89c9a9dbc5 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 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