Skip to content

Commit

Permalink
chore: wrap node writes in p-queue to match webhid
Browse files Browse the repository at this point in the history
  • Loading branch information
nytamin committed Dec 5, 2024
1 parent 55b93c3 commit b3d2f39
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"dependencies": {
"@xkeys-lib/core": "3.2.0",
"node-hid": "^3.0.0",
"p-queue": "^6.6.2",
"tslib": "^2.4.0"
},
"optionalDependencies": {
Expand Down
13 changes: 10 additions & 3 deletions packages/node/src/node-hid-wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/unbound-method */
import { HIDDevice } from '@xkeys-lib/core'
import { EventEmitter } from 'events'
import Queue from 'p-queue'
import * as HID from 'node-hid'

/**
Expand All @@ -10,6 +11,8 @@ import * as HID from 'node-hid'
export class NodeHIDDevice extends EventEmitter implements HIDDevice {
static CLOSE_WAIT_TIME = 300

private readonly writeQueue = new Queue({ concurrency: 1 })

constructor(private device: HID.HIDAsync) {
super()

Expand All @@ -18,9 +21,13 @@ export class NodeHIDDevice extends EventEmitter implements HIDDevice {
}

public write(data: number[]): void {
this.device.write(data).catch((err) => {
this.emit('error', err)
})
this.writeQueue
.add(async () => {
await this.device.write(data)
})
.catch((err) => {
this.emit('error', err)
})
}

public async close(): Promise<void> {
Expand Down

0 comments on commit b3d2f39

Please sign in to comment.