Added Repository
This commit is contained in:
parent
f15d4085c6
commit
37a7074aea
46
src/PrinterRepository.mts
Normal file
46
src/PrinterRepository.mts
Normal 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
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user