Cleanroom
Compose your business logic into commands that validate input.
Status
Installation
npm install cleanroom --save
Example
;Commandstatic schema =properties:email: type: 'string' format: 'email'name: type: 'string'newsletter_subscribe: type: 'boolean'required: 'email' 'name'additionalProperties: falsestatic {const user = inputs;// Do something with the user like save to a database.// ...return user;}Cleanroom;// Sometime later in a file far, far away....{const outcome = UserSignUp// Then check to see if it worked:if outcomesuccessreturn message: `Great success, !` ;elsereturn errors: outcomeerrors ;}
Some things to note about the example:
- Inputs are validated using a JSON Schema
- We can guarentee inputs pass the schema before reaching the business logic
- If
additionalProperties
is set to false, any additional properties will be removed. - This code is completely re-usable in other contexts
How do I call commands?
You have three choices. Given a command UserSignUp, you can do this:
const outcome = UserSignUp;if outcomesuccessconsole;elseconsole;
Or, you can do this:
// returns the result of ::execute(), or throws ValidationErrortryconst result = UserSignUp;console;catch econsole;
Or, you can do this:
// returns a Promise with the result of ::execute() as the resolved value,// or rejects with the validation errors.UserSignUp;
How do I define commands?
- Extend Cleanroom.Command:
Command
- Define your input schema:
Schemas are defined using the JSON Schema specification. See Understanding JSON Schema for basics on JSON Schema.
Commandstatic schema =properties:name: type: 'string' maxLength: 10state: type: 'string' enum: 'AL' 'AK' 'AR' ...age: type: 'integer'isSpecial: type: 'boolean' default: trueaccount: type: 'object'tags: type: 'array' items: type: 'string'prefs:type: 'object'properties:smoking: type: 'boolean'view: type: 'boolean'additionalProperties: falserequired: 'name' 'state' 'age' 'isSpecial' 'account'additionalProperties: false
- Define your execute function. It can return a value:
Commandstatic schema =// ...static {const record = ;// ...return record;}
- Initialize your command:
Cleanroom;
What about validation errors?
Validations are handled by the ajv library by epoberezkin.
Please see the ajv documenation until an overview of validation errors is written.
Acknowledgements
Highly inspired by cypriss/mutations from the Ruby world.