Adrià Vilanova MartÃnez | 7f1e8ea | 2022-10-14 15:50:11 +0200 | [diff] [blame] | 1 | import {arrayBufferToBase64} from './common.js'; |
| 2 | import * as pb from './proto/main_pb.js'; |
| 3 | |
| 4 | export const kWorkflowsDataKey = 'workflowsData'; |
| 5 | |
| 6 | export default class WorkflowsStorage { |
| 7 | static getAll(asProtobuf = false) { |
| 8 | return new Promise(res => { |
| 9 | chrome.storage.local.get(kWorkflowsDataKey, items => { |
| 10 | const workflows = items[kWorkflowsDataKey]; |
| 11 | if (!Array.isArray(workflows)) return res([]); |
| 12 | if (!asProtobuf) return res(workflows); |
| 13 | |
| 14 | workflows.map(w => { |
| 15 | w.proto = pb.workflows.Workflow.deserializeBinary(w?.data); |
| 16 | delete w.data; |
| 17 | }); |
| 18 | return res(workflows); |
| 19 | }); |
| 20 | }); |
| 21 | } |
| 22 | |
| 23 | static get(uuid, asProtobuf = false) { |
| 24 | return this.getAll(asProtobuf).then(workflows => { |
| 25 | for (const w of workflows) { |
| 26 | if (w.uuid == uuid) return w; |
| 27 | } |
| 28 | return null; |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | static exists(uuid) { |
| 33 | return this.get(uuid).then(w => w !== null); |
| 34 | } |
| 35 | |
| 36 | static addRaw(base64Workflow) { |
| 37 | const w = { |
| 38 | uuid: self.crypto.randomUUID(), |
| 39 | data: base64Workflow, |
| 40 | }; |
| 41 | return this.getAll().then(workflows => { |
| 42 | workflows.push(w); |
| 43 | const items = {}; |
| 44 | items[kWorkflowsDataKey] = workflows; |
| 45 | chrome.storage.local.set(items); |
| 46 | }); |
| 47 | } |
| 48 | |
| 49 | static add(workflow) { |
| 50 | const binaryWorkflow = workflow.serializeBinary(); |
| 51 | return arrayBufferToBase64(binaryWorkflow).then(data => { |
| 52 | return this.addRaw(data); |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | static remove(uuid) { |
| 57 | return this.getAll().then(workflows => { |
| 58 | const items = {}; |
| 59 | items[kWorkflowsDataKey] = workflows.filter(w => w.uuid != uuid); |
| 60 | chrome.storage.local.set(items); |
| 61 | }); |
| 62 | } |
| 63 | } |