-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample.js
More file actions
79 lines (61 loc) · 1.93 KB
/
example.js
File metadata and controls
79 lines (61 loc) · 1.93 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
const Hyperschema = require('hyperschema')
const SCHEMA_DIR = './spec/hyperschema'
const schema = Hyperschema.from(SCHEMA_DIR)
const ns1 = schema.namespace('example')
ns1.register({
name: 'request1',
fields: [
{ name: 'field1', type: 'uint' },
{ name: 'field2', type: 'string' }
]
})
ns1.register({
name: 'request2',
fields: [
{ name: 'field1', type: 'string' },
{ name: 'field2', type: 'uint' }
]
})
// Write the schema to disk
Hyperschema.toDisk(schema)
const Hyperdispatch = require('hyperdispatch')
const DISPATCH_DIR = './spec/hyperdispatch'
const hyperdispatch = Hyperdispatch.from(SCHEMA_DIR, DISPATCH_DIR)
const ns2 = hyperdispatch.namespace('example')
// Define commands and associate them with requests
ns2.register({
name: 'command1',
requestType: '@example/request1'
})
ns2.register({
name: 'command2',
requestType: '@example/request1'
})
ns2.register({
name: 'command3',
requestType: '@example/request2'
})
// Write the hyperdispatch configuration to disk
Hyperdispatch.toDisk(hyperdispatch)
const { Router, encode } = require('./spec/hyperdispatch')
const router = new Router()
// Register handlers for commands
router.add('@example/command1', (data, context) => {
console.log('Handler for command1 executed:', data, context)
return { success: true }
})
router.add('@example/command2', (data, context) => {
console.log('Handler for command2 executed:', data, context)
return { success: true }
})
router.add('@example/command3', (data, context) => {
console.log('Handler for command3 executed:', data, context)
return { success: true }
})
const context = { user: 'exampleUser' }
// Dispatch a command1 message
const encodedMessage1 = encode('@example/command1', { field1: 42, field2: 'hello' })
router.dispatch(encodedMessage1, context)
// Dispatch a command3 message
const encodedMessage2 = encode('@example/command3', { field1: 'world', field2: 99 })
router.dispatch(encodedMessage2, context)