Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const Item = require('../model/Item');
- const config = require('../data/config');
- async function addItem(request, h) {
- const cache = request.server.plugins.Cache.cache;
- const config = request.server.plugins.Config.config;
- const payload = request.payload;
- let id_number = await cache.get('id_number');
- id_number = id_number ? id_number : "0";
- let item = new Item(id_number, payload.description);
- const key = {
- "segment": "to-do",
- "id": id_number
- };
- await cache.set(key, item, config.cacheTimeline); // ttl- 1 Day
- id_number = "" + (parseInt(id_number) + 1);
- await cache.set('id_number', id_number, config.cacheTimeline);
- return item;
- }
- async function removeItem(request, h) {
- try {
- const cache = request.server.plugins.Cache.cache;
- const id = request.params.id;
- const item = await cache.get({"id": "" + id});
- if (item === null)
- return h.response("Item doesn't exists").code(404);
- await cache.drop({'id': "" + id});
- return item;
- } catch (e) {
- console.log(e);
- return e;
- }
- }
- async function editItem(request, h) {
- try {
- const cache = request.server.plugins.Cache.cache;
- const config = request.server.plugins.Config.config;
- const payload = request.payload;
- const id = request.params.id + "";
- const item = await cache.get({'id': id});
- if (item === null)
- return h.response("Item doesn't exist").code(404);
- if (item.state === "COMPLETE")
- return h.response("Item already complete").code(400);
- item.state = payload.state;
- item.description = payload.description;
- const key = {
- "segment": "to-do",
- "id": id
- };
- await cache.set(key, item, config.cacheTimeline); // ttl- 1 Day
- return item;
- } catch (e) {
- console.log(e)
- return e;
- }
- }
- async function listItens(request, h) {
- const cache = request.server.plugins.Cache.cache;
- let id_number = await cache.get('id_number');
- id_number = id_number ? parseInt(id_number) : 0;
- const query = request.query;
- const orderBy = query.orderBy;
- const filter = query.filter;
- let list = [];
- for (let i = 0; i <= id_number; i++) {
- let item = await cache.get({
- 'id': '' + i
- });
- if (item)
- list.push(item);
- }
- if (orderBy) {
- const property = (() => {
- switch (query.orderBy) {
- case 'DESCRIPTION':
- return "description";
- case 'DATE_ADDED':
- default:
- return "dateAdded";
- }
- })();
- list.sort((a, b) => (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0);
- }
- if (filter)
- list = list.filter((item) => item.state === query.filter || query.filter === "ALL");
- return list;
- }
- module.exports = {
- addItem,
- removeItem,
- editItem,
- listItens
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement