Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const path = require('path');
- const pathBaseFile = path.join(__dirname, '../config/database.json');
- class Cube {
- constructor(name, description, imageUrl, difficultyLevel) {
- this.name = name;
- this.description = description;
- this.imageUrl = imageUrl;
- this.difficultyLevel = difficultyLevel;
- }
- save() {
- fs.readFile(pathBaseFile, (err, data) => {
- if (err) {
- return console.log(err);
- }
- const cubes = JSON.parse(data);
- this.id = String(cubes.length);
- cubes.push(this);
- fs.writeFile(pathBaseFile, JSON.stringify(cubes), () => {
- console.log('Cubes was successfully saved to database!');
- });
- });
- }
- static find(criteria, cb) {
- if (!cb) {
- cb = criteria;
- criteria = {};
- }
- const { search = null, from = null, to = null } = criteria;
- fs.readFile(pathBaseFile, (err, data) => {
- if (err) {
- return console.log(err);
- }
- const cubes = JSON.parse(data).filter(cube => {
- return (from && to)
- ? cube.name.toLowerCase().includes(search.toLowerCase()) && cube.difficultyLevel >= Number(from) && cube.difficultyLevel <= Number(to)
- : search ? cube.name.toLowerCase().includes(search.toLowerCase()) : cube
- })
- cb(cubes);
- });
- }
- static findById(id, cb) {
- this.find({ id }, (cubes) => {
- const cube = cubes.find(cube => cube.id === id);
- cb(cube);
- })
- }
- }
- module.exports = Cube;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement