Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update example.js #2

Merged
merged 2 commits into from
Jan 31, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 43 additions & 19 deletions example.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,37 @@
const Hyperschema = require('hyperschema')
const Hyperdispatch = require('.')

const SCHEMA_DIR = './output/hyperschema'
const DISPATCH_DIR = './output/hyperdispatch'
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'
}
{ name: 'field1', type: 'uint' },
{ name: 'field2', type: 'string' }
]
})

ns1.register({
name: 'request2',
fields: [
{
name: 'field1',
type: 'string'
},
{
name: 'field2',
type: 'uint'
}
{ 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'
Expand All @@ -52,4 +45,35 @@ ns2.register({
requestType: '@example/request2'
})

// Write the hyperdispatch configuration to disk
Hyperdispatch.toDisk(hyperdispatch)

const { Router, dispatch } = 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 = dispatch('@example/command1', { field1: 42, field2: 'hello' })
router.dispatch(encodedMessage1, context)

// Dispatch a command3 message
const encodedMessage2 = dispatch('@example/command3', { field1: 'world', field2: 99 })
router.dispatch(encodedMessage2, context)
Loading