-
Notifications
You must be signed in to change notification settings - Fork 0
/
records.js
executable file
·99 lines (88 loc) · 2.13 KB
/
records.js
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
const fs = require('fs')
function generateRandomId() {
return Math.floor(Math.random() * 10000)
}
function save(data) {
return new Promise((resolve, reject) => {
fs.writeFile('data.json', JSON.stringify(data, null, 2), (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
/**
* Gets all quotes
* @param None
*/
function getQuotes() {
return new Promise((resolve, reject) => {
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
const json = JSON.parse(data)
resolve(json)
}
})
})
}
/**
* Gets a specific quote by ID
* @param {number} id - Accepts the ID of the specified quote.
*/
async function getQuote(id) {
const quotes = await getQuotes()
return quotes.records.find((record) => record.id == id)
}
/**
* Gets a random quote
* @param None
*/
async function getRandomQuote() {
const quotes = await getQuotes()
const randNum = Math.floor(Math.random() * quotes.records.length)
return quotes.records[randNum]
}
/**
* Creates a new quote record
* @param {Object} newRecord - Object containing info for new quote: the quote text, author and year
*/
async function createQuote(newRecord) {
const quotes = await getQuotes()
newRecord.id = generateRandomId()
quotes.records.push(newRecord)
await save(quotes)
return newRecord
}
/**
* Updates a single record
* @param {Object} newQuote - An object containing the changes to quote: quote, author, year (all optional)
*/
async function updateQuote(newQuote) {
const quotes = await getQuotes()
const quote = quotes.records.find((item) => item.id == newQuote.id)
quote.quote = newQuote.quote
quote.author = newQuote.author
quote.year = newQuote.year
await save(quotes)
}
/**
* Deletes a single record
* @param {Object} record - Accepts record to be deleted.
*/
async function deleteQuote(record) {
const quotes = await getQuotes()
quotes.records = quotes.records.filter((item) => item.id != record.id)
await save(quotes)
}
module.exports = {
getQuotes,
getQuote,
createQuote,
updateQuote,
deleteQuote,
getRandomQuote,
}