-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
102 lines (84 loc) · 2.48 KB
/
index.js
File metadata and controls
102 lines (84 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { readFileSync, writeFileSync } from 'fs';
import express from 'express';
import cors from 'cors';
const FILE_PATH = './listings.json';
const app = express()
const PORT = 3000;
app.use(express.json());
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send(readDB())
})
app.post('/add', (req, res) => {
console.log("1");
const newListing = req.body;
addListing(newListing);
res.json({ success: true, message: "Listing added successfully", listing: newListing });
});
app.get('/hello', (req, res) => {
res.send('Hello Worlferfrd!')
})
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}`)
})
// Read database
const readDB = () => {
const data = readFileSync(FILE_PATH, 'utf8');
return JSON.parse(data);
};
// Write database
const writeDB = (data) => {
try {
writeFileSync(FILE_PATH, JSON.stringify(data, null, 2), 'utf8');
console.log("3");
} catch (error) {
console.error("❌ error in JSON", error);
}
};
// Create a new listing
const addListing = (listing) => {
const db = readDB();
listing.id = db.length ? db[db.length - 1].id + 1 : 1; // Auto-increment ID
db.push(listing);
console.log("2");
writeDB(db);
};
// Read all listings
const getAllListings = () => readDB();
// Read a single listing by ID
const getListingById = (id) => {
const db = readDB();
return db.find(listing => listing.id === id) || null;
};
// Update a listing
const updateListing = (id, newData) => {
const db = readDB();
const index = db.findIndex(listing => listing.id === id);
if (index !== -1) {
db[index] = { ...db[index], ...newData };
writeDB(db);
return true;
}
return false;
};
// Delete a listing
const deleteListing = (id) => {
let db = readDB();
const newDb = db.filter(listing => listing.id !== id);
if (newDb.length !== db.length) {
writeDB(newDb);
return true;
}
return false;
};
// Example Usage in development environment
// console.log("All Listings:", getAllListings());
// addListing({ title: "Gaming Chair", category: "furniture", price: 500, description: "Comfortable gaming chair", imageUrl: "https://images.unsplash.com/photo-1597670351082-4c255af69ab6?w=500", intra: "john_doe" });
// console.log("After Adding:", getAllListings());
// console.log("Get Listing with ID 1:", getListingById(1));
// updateListing(1, { price: 7500 });
// console.log("After Update:", getAllListings());
// deleteListing(2);
// console.log("After Deletion:", getAllListings());
export default { readDB, writeDB };