Files
traveldrafter/web/datastore.js

126 lines
2.0 KiB
JavaScript

export class LocationsDataStore {
constructor() {
this.data = {};
this.read();
}
read() {
this.data = DataStore.get("locations") || {};
}
write() {
DataStore.set("locations", this.data);
}
rememberAll(location_list) {
for (let location of location_list) {
this.data[location.id] = location;
}
this.write();
}
rememberAllIfNotExist(location_list) {
for (let location of location_list) {
if (!(location.id in this.data)) {
this.data[location.id] = location;
}
}
this.write();
}
}
export class RecentLocationsDataStore {
constructor() {
this.data = [];
this.read();
}
read() {
this.data = DataStore.get("recent-locations") || [];
}
write() {
DataStore.set("recent-locations", this.data);
}
remember(location_id) {
this.data = this.data.filter((item) => {
return item != location_id;
});
this.data.push(location_id);
this.write();
}
}
export class TrackedTripsDataStore {
constructor() {
this.data = [];
this.read();
}
read() {
this.data = DataStore.get("tracked-trips") || [];
}
write() {
DataStore.set("tracked-trips", this.data);
}
remember(trip_id, origin_id, destination_id) {
this.data.push({
trip: trip_id,
origin: origin_id,
destination: destination_id,
});
this.write();
}
}
export class TripsDataStore {
constructor() {
this.data = {};
this.read();
}
read() {
this.data = DataStore.get("trips") || {};
}
write() {
DataStore.set("trips", this.data);
}
remember(trip) {
this.rememberAll([trip]);
}
rememberAll(trip_list) {
for (let trip of trip_list) {
this.data[trip.id] = trip;
}
this.write();
}
}
export class DataStore {
static get(key) {
return JSON.parse(window.localStorage.getItem(key));
}
static set(key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
}
constructor() {
this.locations = new LocationsDataStore();
this.recent_locations = new RecentLocationsDataStore();
this.tracked_trips = new TrackedTripsDataStore();
this.trips = new TripsDataStore();
}
}