-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.ts
97 lines (86 loc) · 2.95 KB
/
block.ts
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
import { defineStore } from 'pinia';
import { useRegattaStore } from './regatta';
import { Block, NewBlock } from '~~/models/block';
import { useBlockService } from '~~/composables/useBlockService';
const blockService = useBlockService();
import { useToastService } from '~~/composables/useToastService';
const { showError } = useToastService();
interface BlockState {
ids: string[];
entities: { [id: string]: Block };
selectedId: string | null;
}
export const useBlockStore = defineStore('blocks', {
state: (): BlockState => ({
ids: [],
entities: {},
selectedId: null
}),
getters: {
allBlocks(state: BlockState) {
return state.ids
.map((id: string) => state.entities[id])
.sort((a: Block, b: Block) => a.block - b.block);
},
selectedBlock(state: BlockState) {
return (
(state.selectedId && state.entities[state.selectedId]) || null
);
}
},
actions: {
async loadBlocks() {
const regattaId = useRegattaStore().selectedId;
if (regattaId == null) {
return;
}
try {
const loadedBlocks = await blockService.loadBlocks(regattaId);
const blockIds = loadedBlocks.map((block) => block.id);
const blockEntities = loadedBlocks.reduce(
(entities: { [id: string]: Block }, block: Block) => {
return { ...entities, [block.id]: block };
},
{}
);
this.ids = blockIds;
this.entities = blockEntities;
} catch (error) {
console.error(error);
useToastService().showError(
'Something went wrong loading the blocks'
);
}
},
async add(newBlock: NewBlock) {
try {
const block = await blockService.addBlock(newBlock);
this.ids = [...this.ids, block.id];
this.entities = {
...this.entities,
[block.id]: block
};
} catch (error) {
console.error(error);
useToastService().showError(
'Something went wrong adding the new block'
);
}
},
delete(id: string) {
this.ids.splice(this.ids.indexOf(id), 1);
delete this.entities[id];
},
async edit(id: string, data: NewBlock) {
try {
const editedRower = await blockService.editBlock(id, data);
this.entities[id] = editedRower;
} catch (error) {
console.error(error);
useToastService().showError(
'Something went wrong editing the block'
);
}
}
}
});