{"library":"machine-as-action","title":"Machine as Action Controller","description":"machine-as-action is a Node.js utility designed to bridge the gap between 'machines' – a pattern for encapsulating reusable business logic – and standard HTTP/WebSocket request-response cycles. It allows developers to define a machine and then wrap it with `asAction` to automatically handle incoming request parameters as machine inputs and map machine exits to various HTTP response types, including JSON data, rendered views, or redirects. The current stable version is 10.3.1, though recent release notes show significant changes around version 7.x. While there isn't a strict, rapid release cadence apparent from the provided data, updates have been made. Its primary differentiator lies in its deep integration with the 'machine' pattern, providing a structured and convention-over-configuration approach to expose API endpoints, particularly useful in frameworks like Sails.js where machines are a core architectural component. It offers granular control over response status codes and view rendering based on the outcome of a machine's execution, aiming to reduce boilerplate in controller logic.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install machine-as-action"],"cli":null},"imports":["const asAction = require('machine-as-action');"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"const asAction = require('machine-as-action');\n\n// Simulate Express/Sails req/res objects for demonstration\nconst mockReq = (query = {}, body = {}) => ({ query, body });\nconst mockRes = () => {\n  let _status = 200;\n  let _data = null;\n  let _view = null;\n  let _redirect = null;\n\n  return {\n    status: function(code) { _status = code; return this; },\n    json: function(data) { _data = data; console.log(`[Response JSON] Status: ${_status}, Data: ${JSON.stringify(_data)}`); },\n    send: function(data) { _data = data; console.log(`[Response Send] Status: ${_status}, Data: ${data}`); },\n    view: function(template, locals) { _view = { template, locals }; console.log(`[Response View] Status: ${_status}, Template: ${_view.template}, Locals: ${JSON.stringify(_view.locals)}`); },\n    redirect: function(url) { _redirect = url; console.log(`[Response Redirect] Status: ${_status}, URL: ${_redirect}`); },\n    serverError: function(err) { _status = 500; _data = { error: err.message }; console.error(`[Server Error] Status: ${_status}, Data: ${JSON.stringify(_data)}`); }\n  };\n};\n\n// 1. Define an inline machine\nconst greetMachine = {\n  inputs: {\n    name: { type: 'string', required: true, example: 'World' }\n  },\n  exits: {\n    success: { outputExample: 'Hello World!' },\n    error: { outputExample: 'Could not greet.' }\n  },\n  fn: function(inputs, exits) {\n    if (inputs.name) {\n      return exits.success(`Hello, ${inputs.name}!`);\n    }\n    return exits.error(new Error('Name input is missing.'));\n  }\n};\n\n// 2. Wrap the machine as an action\nconst greetAction = asAction(greetMachine);\n\n// 3. Simulate an HTTP request for greetAction\nconsole.log('--- Simulating a simple custom action ---');\ngreetAction(mockReq({ name: 'Registry User' }), mockRes());\n\n// 4. Define an action with a custom responseType (e.g., 'view')\nconst showProfilePageAction = asAction({\n  inputs: {\n    userId: { type: 'string', required: true, example: 'user-123' }\n  },\n  exits: {\n    success: {\n      responseType: 'view',\n      viewTemplatePath: 'profile/show',\n      outputExample: { username: 'Alice', id: 'user-123' }\n    }\n  },\n  fn: function(inputs, exits) {\n    // In a real app, this would fetch user data from a database\n    const userData = { username: `User ${inputs.userId}`, id: inputs.userId };\n    return exits.success(userData);\n  }\n});\n\n// 5. Simulate an HTTP request for the view action\nconsole.log('\\n--- Simulating an action rendering a view ---');\nshowProfilePageAction(mockReq({ userId: '456' }), mockRes());","lang":"javascript","description":"This quickstart demonstrates how to wrap an inline machine with `asAction` and simulate its execution using mock `req` and `res` objects. It covers basic JSON responses and advanced view rendering, illustrating how machine outputs are mapped to HTTP responses.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}