diff --git a/src/PrinterRepository.mts b/src/PrinterRepository.mts new file mode 100644 index 0000000..10f4d41 --- /dev/null +++ b/src/PrinterRepository.mts @@ -0,0 +1,46 @@ +import { Printer } from './Printer.mjs' +import fs from 'fs' + +export class PrinterRepository { + constructor() { + if (PrinterRepository.instance) return PrinterRepository.instance + + this.loadFromJSON() + PrinterRepository.instance = this + } + + private printers: Printer[] = [] + static instance: PrinterRepository + + loadFromJSON() { + const json = JSON.parse(fs.readFileSync('./data/printers.json', 'utf8')) + this.printers = json.map( + ({ name, ip, model }: Printer) => new Printer(name, ip, model) + ) + } + + saveToJSON() { + const json = JSON.stringify(this.printers) + fs.writeFileSync('./data/printers.json', json, 'utf8') + } + + addPrinter(printer) { + this.printers.push(printer) + this.saveToJSON() + } + + removePrinter(printerName) { + this.printers = this.printers.filter( + printer => printer.name !== printerName + ) + this.saveToJSON() + } + + getPrinter(printerName) { + return this.printers.find(printer => printer.name === printerName) + } + + getAllPrinters() { + return this.printers + } +} diff --git a/src/index.ts b/src/index.ts index 7854ca6..939184f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,7 @@ const printers: Printer[] = printersDB.map( printer => new Printer(printer.name, printer.ip, printer.model) ) -app.get('/', async (req, res) => { +app.get('/api/printer', async (req, res) => { const printersInfo: PrinterInfo[] = await Promise.all( printers.map(printer => printer.getPrinterInfo()) ) @@ -21,7 +21,7 @@ app.get('/', async (req, res) => { res.send(printersInfo) }) -app.get('/:printerName', async (req, res) => { +app.get('/api/printer/:printerName', async (req, res) => { const printerName = req.params.printerName const printer = printers.find(printer => printer.name === printerName)