My domain is quite simple. I have a Message
class, and a MessagesManager
class.
Message
has 3 attributes:
author
message
(body)timestamp
MessagesManager
is basically just an interface that keeps the history of messages, adds new messages etc.
I want to store the messages in localStorage
so that they can be retrieved at later points, yet I'm not sure how to do it.
class MessagesManager {
constructor() {
this.msgs = []; //retrieve from localStorage
}
add(author, message) {
var msg = new Message(author, message)
this.msgs.push(msg);
}
save() {
// save to localStorage
}
delete() {
this.msgs = [];
}
}
And my Message
:
class Message {
constructor(author, message) {
this.timestamp = Date.now();
this.author = author;
this.message = message;
}
toString() {
var date = new Date(this.timestamp);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = "[" + [hours, minutes, seconds].join(":") + "]";
return time + " " + this.author + ": " + this.message;
}
}
What is the nicest/best way to store the messages (as objects, kind of) in the localStorage
, while also being able to retrieve them easily (ie. in MessagesManager
contructor)?