https://github.com/ripeworks/async-interactor
Interactor pattern using async/await
https://github.com/ripeworks/async-interactor
Last synced: 11 months ago
JSON representation
Interactor pattern using async/await
- Host: GitHub
- URL: https://github.com/ripeworks/async-interactor
- Owner: ripeworks
- License: mit
- Created: 2017-04-20T20:31:08.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2017-05-04T20:46:55.000Z (almost 9 years ago)
- Last Synced: 2025-03-06T21:41:51.063Z (11 months ago)
- Language: JavaScript
- Size: 45.9 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
async interactor
## Getting Started
```sh
$ npm install --save async-interactor
```
_NOTE: async/await support required from node 7.6.0+ or something like [async-to-gen](https://github.com/leebyron/async-to-gen)_
## Usage
```js
import Interactor from 'async-interactor'
class AuthenticateUser extends Interactor {
async call () {
const {username, password} = this.context
const user = await db.where({username, password}).find()
if (!user) {
this.fail('User not found')
}
this.context.user = user
}
}
// example route handler
app.post('/login', async (req, res) => {
const result = await AuthenticateUser.call(req.params)
if (result.success) {
res.send({success: true, user: result.user})
}
})
```
## Organizers
```js
import Interactor from 'async-interactor'
class AddSubscription extends Interactor {
// return Array of interactors
organize () {
return [AuthenticateUser, FinalizePayment]
}
}
app.post('/buy', async (req, res) => {
const result = await AddSubscription.call(req.params)
})
```
## Errors
By default any errors thrown inside of an interactor are swallowed and return in the result of the interactor. This allows you to check the result of the interactor after it runs, regardless of a success or failure. There is a `throwOnError` option available if you don't want this default behavior.
```js
class ThisWillThrow extends Interactor {
throwOnError = true
async call () {
throw new Error('Boom')
}
}
const result = await ThisWillThrow.call({})
console.log(result) // <- this never runs because the error is `thrown`
```