-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathevents.js
More file actions
92 lines (85 loc) · 2.36 KB
/
Copy pathevents.js
File metadata and controls
92 lines (85 loc) · 2.36 KB
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
/*
* Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved.
*/
'use strict';
const JsonLdError = require('./JsonLdError');
const {
isArray: _isArray
} = require('./types');
const {
asArray: _asArray
} = require('./util');
const api = {};
module.exports = api;
/**
* Handle an event.
*
* Top level APIs have a common 'eventHandler' option. This option can be a
* function, array of functions, object mapping event.code to functions (with a
* default to call next()), or any combination of such handlers. Handlers will
* be called with an object with an 'event' entry and a 'next' function. Custom
* handlers should process the event as appropriate. The 'next()' function
* should be called to let the next handler process the event.
*
* The final default handler will use 'console.warn' for events of level
* 'warning'.
*
* @param {object} event - event structure:
* {string} code - event code
* {string} level - severity level, one of: ['warning']
* {string} message - human readable message
* {object} details - event specific details
* @param {object} options - processing options
*/
api.handleEvent = ({
event,
options
}) => {
const handlers = [].concat(
options.eventHandler ? _asArray(options.eventHandler) : [],
_defaultHandler
);
_handle({event, handlers});
};
function _handle({event, handlers}) {
let doNext = true;
for(let i = 0; doNext && i < handlers.length; ++i) {
doNext = false;
const handler = handlers[i];
if(_isArray(handler)) {
doNext = _handle({event, handlers: handler});
} else if(typeof handler === 'function') {
handler({event, next: () => {
doNext = true;
}});
} else if(typeof handler === 'object') {
if(event.code in handler) {
handler[event.code]({event, next: () => {
doNext = true;
}});
} else {
doNext = true;
}
} else {
throw new JsonLdError(
'Invalid event handler.',
'jsonld.InvalidEventHandler',
{event});
}
}
return doNext;
}
function _defaultHandler({event}) {
if(event.level === 'warning') {
console.warn(`WARNING: ${event.message}`, {
code: event.code,
details: event.details
});
return;
}
// fallback to ensure events are handled somehow
throw new JsonLdError(
'No handler for event.',
'jsonld.UnhandledEvent',
{event});
}