UNPKG

@on-time/core

Version:

core business logic for OT API

70 lines (65 loc) 2.01 kB
const assert = require('assert'); class Controller { constructor(service) { this.service = service; this.post = this.post.bind(this); this.get = this.get.bind(this); this.put = this.put.bind(this); this.delete = this.delete.bind(this); } /** * Creates a resource with data extracted from http request body. * @param request * @returns {Promise<{error: *, status: number}|{body: *, status: number}>} */ async post(request){ try { assert(request.body); const data = await this.service.create(request.body); return { data, status: 201 } } catch (error) { return { error, status: 500 } } } /** * Fetches and returns all resources matching query * @param request * @returns {Promise<{error: *, status: number}|{body: *, status: number}>} */ async get(request){ try { assert(request.body); const data = await this.service.getAll(request.body); return { body: data, status: 200 } } catch (error) { return { error, status: 500 } } } /** * Handles PUT requests * @param request * @returns {Promise<{error: *, status: number}|{body: *, status: number}>} */ async put(request){ try{ const data = await this.service.update(request.params.id, request.body); return { body: data, status: 200 } } catch (error) { return { error, status: 500 } } } /** * Handles DELETE requests * @param request * @returns {Promise<{error: *, status: number}|{body: *, status: number}>} */ async delete(request){ try{ const data = await this.service.delete(request.params.id); return { body: data, status: 200 } } catch (error) { return { error, status: 500 } } } } module.exports = Controller;