Command object Interface for JavaScript, a port of the Ruby gem Serviz.
Serviz-JS
provides a minimal interface to unify and homogenize your Service or Command objects in your JavaScript applications. It works in both Node.js and browser environments.
npm install serviz
- Your class should extend from
Serviz
- Your class should implement a
call()
method - Return the result via
this.result = value
- Add errors via
this.errors.push('error message')
- Check the status via the provided
success()
orfailure()
methods
First, you should create a Service class:
import { Serviz } from 'serviz'
class RegisterUser extends Serviz {
constructor(user) {
super()
this.user = user
}
call() {
if (this.user && this.user.email) {
// Simulate user registration
this.result = {
id: Math.random().toString(36),
...this.user,
registeredAt: new Date()
}
} else {
this.errors.push('Invalid user data')
}
}
}
Now, you can run it by using the call
method:
const operation = RegisterUser.call({ name: 'John', email: 'john@example.com' })
if (operation.success()) {
const user = operation.result
console.log(`Success! ${user.name} registered!`)
} else {
console.log(`Error! ${operation.errorMessages()}`)
}
As you can see in the example above, you can use the success()
method to check if your operation succeeded. You can also use the ok()
alias.
In case you want to check if the operation failed, you can use the failure()
method (or the alias error()
):
if (operation.failure()) {
console.log("Error! Please try again...")
return
}
You may like to use the callback style by passing a callback function as the last argument to call
:
RegisterUser.call(user, (operation) => {
if (operation.ok()) console.log("Success!")
})
Serviz-JS
also provides a ServizWorkflow
class that allows you to compose multiple service objects together using a clean, declarative API for orchestrating complex multi-step operations.
import { ServizWorkflow } from 'serviz'
class UserOnboarding extends ServizWorkflow {}
UserOnboarding.step(ValidateUser)
UserOnboarding.step(RegisterUser, {
if: (lastStep) => lastStep && lastStep.success()
})
UserOnboarding.step(SendWelcomeEmail, {
params: (instance) => instance._lastStep.result,
if: (lastStep) => lastStep && lastStep.success()
})
// Usage
const operation = UserOnboarding.call({
name: 'John Doe',
email: 'john@example.com'
})
console.log(operation.success()) // => true
console.log(operation.result) // => result from SendWelcomeEmail
// Handles failures gracefully
const failedOperation = UserOnboarding.call({
name: 'Jane Doe'
// Missing email
})
console.log(failedOperation.failure()) // => true
console.log(failedOperation.errors) // => ["Email is required"]
- Conditional execution using the
if:
option to control whether steps run based on previous results - Error accumulation from all failed steps in the workflow
- Result chaining where the last successful step's result becomes the workflow result
- Full compatibility with the existing Serviz interface (
success()
,failure()
,errors
,result
)
You can also pass custom parameters to individual steps:
class OrderProcessing extends ServizWorkflow {}
OrderProcessing.step(ValidateOrder)
OrderProcessing.step(ChargePayment, {
params: { gateway: 'stripe' },
if: (lastStep) => lastStep.success()
})
OrderProcessing.step(ShipOrder, {
if: (lastStep) => lastStep.success()
})
Serviz-JS
works in browser environments via ES modules:
<script type="module">
import { Serviz, ServizWorkflow } from './node_modules/serviz/src/index.js'
class MyService extends Serviz {
call() {
this.result = 'Hello from browser!'
}
}
const operation = MyService.call()
console.log(operation.result) // "Hello from browser!"
</script>
Or with a bundler like Webpack, Rollup, or Vite:
import { Serviz, ServizWorkflow } from 'serviz'
To contribute to this project:
git clone https://github.com/markets/serviz-js.git
cd serviz-js
npm install
# Run all tests
npm test
# Watch mode
npm run test:watch
Copyright (c) Marc Anguera. Serviz-JS
is released under the MIT License.