Advertisement
Todorov_Stanimir

cube.js

Jun 9th, 2020
776
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const path = require('path');
  3. const pathBaseFile = path.join(__dirname, '../config/database.json');
  4.  
  5. class Cube {
  6.  
  7.     constructor(name, description, imageUrl, difficultyLevel) {
  8.         this.name = name;
  9.         this.description = description;
  10.         this.imageUrl = imageUrl;
  11.         this.difficultyLevel = difficultyLevel;
  12.     }
  13.  
  14.     save() {
  15.         fs.readFile(pathBaseFile, (err, data) => {
  16.             if (err) {
  17.                 return console.log(err);
  18.             }
  19.  
  20.             const cubes = JSON.parse(data);
  21.  
  22.             this.id = String(cubes.length);
  23.  
  24.             cubes.push(this);
  25.  
  26.             fs.writeFile(pathBaseFile, JSON.stringify(cubes), () => {
  27.                 console.log('Cubes was successfully saved to database!');
  28.             });
  29.         });
  30.     }
  31.  
  32.     static find(criteria, cb) {
  33.         if (!cb) {
  34.             cb = criteria;
  35.             criteria = {};
  36.         }
  37.         const { search = null, from = null, to = null } = criteria;
  38.         fs.readFile(pathBaseFile, (err, data) => {
  39.             if (err) {
  40.                 return console.log(err);
  41.             }
  42.             const cubes = JSON.parse(data).filter(cube => {
  43.                 return (from && to)
  44.                     ? cube.name.toLowerCase().includes(search.toLowerCase()) && cube.difficultyLevel >= Number(from) && cube.difficultyLevel <= Number(to)
  45.                     : search ? cube.name.toLowerCase().includes(search.toLowerCase()) : cube
  46.             })
  47.             cb(cubes);
  48.         });
  49.     }
  50.  
  51.     static findById(id, cb) {
  52.         this.find({ id }, (cubes) => {
  53.             const cube = cubes.find(cube => cube.id === id);
  54.             cb(cube);
  55.         })
  56.     }
  57. }
  58.  
  59. module.exports = Cube;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement