mail/front/src/store/store.js
2023-03-20 21:28:13 +01:00

119 lines
3.9 KiB
JavaScript

import API from "@/services/imapAPI";
import { createStore } from "vuex";
const store = createStore({
state() {
return {
rooms: [
{
id: 0,
user: "clemnce",
userId: 0,
roomName: "Lorem magna minim cillum labore ex eiusmod proident excepteur sint irure ipsum.",
mailboxId: 1,
},
{
id: 1,
user: "juliette",
roomName: "Lorem magna minim cillum labore ex eiusmod proident excepteur sint irure ipsum.",
mailboxId: 1,
},
{
id: 2,
user: "jean",
roomName: "Lorem magna minim cillum labore ex eiusmod proident excepteur sint irure ipsum.",
mailboxId: 2,
},
{
id: 3,
user: "luc",
roomName: "Lorem magna minim cillum labore ex eiusmod proident excepteur sint irure ipsum.",
mailboxId: 2,
},
],
messages: [
],
mailboxes: [],
activeMailbox: 0,
activeRoom: 0
};
},
mutations: {
setActiveMailbox(state, payload) {
state.activeMailbox = payload;
// todo call actions
// fetch rooms for this mailboxes if not already fetched
const mailbox = state.mailboxes.find((mailbox) => mailbox.id == payload);
// todo fetched mailbox all
if (mailbox?.fetched == false) {
API.getRooms(payload).then((res) => {
// todo add if not exist
mailbox.fetched = true;
res.data.forEach((room) => {
room.fetched = false;
state.rooms.push(room);
});
}).catch((err) => {
console.log(err)
});
}
},
setActiveRoom(state, payload) {
state.activeRoom = payload;
// todo call actions
// fetch messages for this room if not already fetched
const room = state.rooms.find((room) => room.id == payload);
if (!room || room?.fetched == false) {
console.log("add messages")
API.getMessages(payload).then((res) => {
// todo add if not exist
room.fetched = true;
res.data.forEach((msg) => {
state.messages.push(msg);
});
}).catch((err) => {
console.log(err)
});
}
},
addMailboxes(state, payload) {
payload.forEach((mailbox) => {
mailbox.fetched = false;
state.mailboxes.push(mailbox);
});
},
},
getters: {
rooms: (state) => () => {
if (state.activeMailbox === 0) return state.rooms;
return state.rooms.filter((room) => room.mailboxId == state.activeMailbox);
},
messages: (state) => (roomId) => {
const room = state.rooms.find((room) => room.id === roomId);
if (room?.fetched === false) {
console.log("ok")
}
return [1, 2];
}
},
actions: {
async fetchMailboxes(context) {
console.log("add mailboxes");
API.getMailboxes()
.then((res) => {
context.commit("addMailboxes", res.data);
})
.catch((err) => {
console.log(err);
});
},
async fetchMessages(context) {
console.log(context)
},
},
});
export default store;