Project

General

Profile

Download (1.44 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / background / storage_server.js @ 6b12a034

1
/**
2
 * Hachette storage through connection (server side)
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Redistribution terms are gathered in the `copyright' file.
6
 */
7

    
8
/*
9
 * IMPORTS_START
10
 * IMPORT listen_for_connection
11
 * IMPORT get_storage
12
 * IMPORT TYPE_PREFIX
13
 * IMPORT CONNECTION_TYPE
14
 * IMPORTS_END
15
 */
16

    
17
var storage;
18

    
19
async function handle_remote_call(port, message)
20
{
21
    let [call_id, func, args] = message;
22

    
23
    try {
24
	let result = await Promise.resolve(storage[func](...args));
25
	port.postMessage({call_id, result});
26
    } catch (error) {
27
	error = error + '';
28
	port.postMessage({call_id, error});
29
    }
30
}
31

    
32
function remove_storage_listener(cb)
33
{
34
    storage.remove_change_listener(cb);
35
}
36

    
37
function new_connection(port)
38
{
39
    console.log("new remote storage connection!");
40

    
41
    port.postMessage({
42
	[TYPE_PREFIX.SCRIPT] : storage.get_all(TYPE_PREFIX.SCRIPT),
43
	[TYPE_PREFIX.BAG] : storage.get_all(TYPE_PREFIX.BAG),
44
	[TYPE_PREFIX.PAGE] : storage.get_all(TYPE_PREFIX.PAGE)
45
    });
46

    
47
    let handle_change = change => port.postMessage(change);
48

    
49
    storage.add_change_listener(handle_change);
50

    
51
    port.onMessage.addListener(m => handle_remote_call(port, m));
52
    port.onDisconnect.addListener(() =>
53
				  remove_storage_listener(handle_change));
54
}
55

    
56
async function start_storage_server()
57
{
58
    storage = await get_storage();
59

    
60
    listen_for_connection(CONNECTION_TYPE.REMOTE_STORAGE, new_connection);
61
}
62

    
63
/*
64
 * EXPORTS_START
65
 * EXPORT start_storage_server
66
 * EXPORTS_END
67
 */
(8-8/8)