grandchef / escpos-buffer

Library to generate buffer for thermal printers.
MIT License
51 stars 17 forks source link

Exposes the async nature of WebUSB #23

Closed tjmgregory closed 2 years ago

tjmgregory commented 2 years ago

Hello!

Theo here - another engineer from @elephant-healthcare, it seems you've worked with the wonderful @noisyscanner in the past. Thanks for the awesome package you've written, it's amazing stuff 🤘 You'll be pleased to hear its being used to assist in saving lives in many LEDCs.

I have for you a fairly big change to this package and to its interface, so have opted to bump the major number. I hope you like what you see 😊

Problem brief

Almost all w3c web usb functions, as typed by @types/w3c-web-usb, are async. In the existing implementation of WebUSB this behaviour was hidden, with all methods providing sync return values.

This meant that should an error occur during any open/write/close, such as the printer having been disconnected, these errors would be uncatchable by the consumer of the package, as they would be thrown outside the main 'thread'. i.e.

try {
  await printer.writeLn('Foo') // The await has no effect as writeLn is sync
} catch (e) {
  // So, this can never be reached
}

Proposed changes

Reasoning

I opted for async factory methods that call initialize as opposed to adding initialization checks to each method call, as this felt less invasive of a change. This also wouldn't require a test being written for every method, nor managing the state of having been initialized.

Testing

All tests are passing and no .bin test files have been changed. The only place this looks a little unclean is in the Daruma.initialize method, where I was unable to use the super.initialize without the the calls to the printer being done in a different order. I wasn't keen to change the bin files, as couldn't be certain of the importance of the ordering.

Have also tested this with a printer connected and it works successfully.

Other

This also bumps Prettier to support the nullish function call operator foo?.() https://github.com/prettier/prettier/issues/6609

tjmgregory commented 2 years ago
image
mazinsw commented 2 years ago

Hi, thanks for the library enhacement, i will set some code review after analisys and prepare for merge, can you explain why not send the usb buffer only after the end, so it does not require async call, but memory call only?