Skip to content

Commit

Permalink
chore: Refactor writeNotificationToFile.js and create notifications.j…
Browse files Browse the repository at this point in the history
…son file if it doesn't exist
  • Loading branch information
necipsagiro committed May 17, 2024
1 parent 5a294f7 commit b93b587
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions utils/writeNotificationToFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ const notificationQueue = async.queue((data, callback) => {
});
}, 1);

if (!fs.existsSync(NOTIFICATION_FILE_PATH))
fs.writeFile(NOTIFICATION_FILE_PATH, '', err => {
if (err)
return logger.error(err);

logger.activity('notifications.json created');
});

const writeNotificationToFile = data => {
if (!data || typeof data != 'object')
return logger.error('bad_request');
Expand All @@ -28,33 +36,26 @@ const writeNotificationToFile = data => {
if (!data.message && typeof data.message != 'string')
return logger.error('bad_request');

if (!fs.existsSync(NOTIFICATION_FILE_PATH))
fs.writeFile(NOTIFICATION_FILE_PATH, '', err => {
if (err)
return logger.error(err);

writeNotificationToFile(data);
});
else
fs.readFile(NOTIFICATION_FILE_PATH, (err, content) => {
if (err)
return logger.error(err);
fs.readFile(NOTIFICATION_FILE_PATH, (err, content) => {
if (err)
return logger.error(err);

const notifications = json.jsonify(content) || [];
const notifications = json.jsonify(content) || [];

data.publish_date = Date.now();
notifications.push(data);
data.publish_date = Date.now();
notifications.push(data);

while (notifications.length > MAX_NOTIFICATIONS)
notifications.shift();
while (notifications.length > MAX_NOTIFICATIONS)
notifications.shift();

fs.writeFile(NOTIFICATION_FILE_PATH, json.stringify(notifications), err => {
if (err)
return logger.error(err);
fs.writeFile(NOTIFICATION_FILE_PATH, json.stringify(notifications), err => {
if (err)
return logger.error(err);

return logger.activity('Notification saved to notifications.json');
});
return logger.activity('Notification saved to notifications.json');
});
});
};

module.exports = data => {
Expand Down

0 comments on commit b93b587

Please sign in to comment.