Added Repository

This commit is contained in:
Douglas Barone 2023-05-15 12:23:33 -04:00
parent f15d4085c6
commit 37a7074aea
2 changed files with 48 additions and 2 deletions

46
src/PrinterRepository.mts Normal file
View File

@ -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
}
}

View File

@ -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)