{"name":"machine-as-action","version":"2.0.2","description":"Run a machine from an HTTP or WebSocket request.","scripts":{"test":"node ./node_modules/mocha/bin/mocha"},"keywords":["machine","action","sails.js","blueprint","websocket","http"],"author":{"name":"Mike McNeil"},"license":"MIT","dependencies":{"lodash":"^3.8.0","machine":"^7.1.0"},"devDependencies":{"mocha":"^2.2.4","sails":"^0.11.0"},"repository":{"type":"git","url":"git+ssh://git@github.com/treelinehq/machine-as-action.git"},"gitHead":"9efed2a69b5a227cf7767a26dc5ecc53c3eb49d1","bugs":{"url":"https://github.com/treelinehq/machine-as-action/issues"},"homepage":"https://github.com/treelinehq/machine-as-action#readme","_id":"machine-as-action@2.0.2","_shasum":"cfd9248ca9fc2b3f9f6b36b8336b47eb9e1bf3ea","_from":".","_npmVersion":"2.8.4","_nodeVersion":"0.10.26","_npmUser":{"name":"mikermcneil","email":"michael.r.mcneil@gmail.com"},"dist":{"shasum":"cfd9248ca9fc2b3f9f6b36b8336b47eb9e1bf3ea","tarball":"http://registry-npm.ywwl.com/machine-as-action/download/machine-as-action-2.0.2.tgz","integrity":"sha512-o4xTPDj0RwcFYzmSQ+2KNWfkQ6Qz2IpUWdbTvwYLcYEmSCnFDSydN33rGhoxkl6JnfS1D2AP5gaBfyU1SJPG/w==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDSxVwg4PcmMVZOs+Xl2ck7rlNKzdSNPt3CbKFEHYrn1wIgJWIAKHztE5n85KpcuDEdETmxzsAXYtQct8e5a+f6my0="}],"size":5501,"noattachment":false,"key":"/machine-as-action/-/machine-as-action-2.0.2.tgz"},"maintainers":[{"name":"mikermcneil","email":"michael.r.mcneil@gmail.com"}],"directories":{},"readme":"# machine-as-action\n\nBuild a modified version of a machine that proxies its inputs from request parameters, and proxies its exits through the response.\n\n```sh\n$ npm install machine-as-action --save\n```\n\n\n## Usage\n\n```js\nvar asAction = require('machine-as-action');\nvar OpenWeather = require('machinepack-openweather');\n\n// WeatherController.js\nmodule.exports = {\n\n  traditionalReqRes: function (req, res) { /* ... */ },\n\n  getLatest: asAction(OpenWeather.getCurrentConditions),\n\n  doSomethingCustom: asAction({\n    exits: {\n      success: {\n        outputExample: 'Some dynamic message like this.'\n      }\n    },\n    fn: function (inputs, exits) {\n      return exits.success('Hello world!');\n    }\n  }),\n\n  // etc...\n\n}\n```\n\nNow you can run your machine using a HTTP or Socket.io request:\n\n```js\n// For example, using jQuery and an out-of-the-box Sails.js route/blueprint configuration:\n$.get('/weather/getLatest', {\n  city: 'San Francisco'\n}, function (weatherData){\n  console.log(weatherData);\n});\n```\n\n> Note that the machine definition you provide here doesn't have to come from an already-published machinepack-- it can be required locally from your project, or declared inline.\n\n\n\n#### Customizing the response\n\nSo sending down data is great, but sometimes you need to render view templates, redirect to dynamic URLs, use a special status code, stream down a file, etc.  No problem.  You can customize the response from each exit using a number of additional,  machine-as-action specific options.\n\n\n```js\nvar asAction = require('machine-as-action');\n\n// WeatherController.js\nmodule.exports = {\n\n  showHomepage: asAction({\n    \n\n    exits: {\n\n      success:{\n        responseType: 'view',\n        viewTemplatePath: 'homepage'\n        // The view will be provided with a \"local\" called `stuff`,\n      }\n\n    },\n\n\n    fn: function(inputs,exits){\n      return exits.success({ stuff: 'things' });\n    }\n    \n\n  })\n};\n```\n\n\nFor each of your exits, you can optionally specify a `responseType`, `status`, and/or `view`.\n\n**responseType** is one of the following:\n + \"\"         (the standard response:  Determine an appropriate response based on context: this might send plain text, download a file, transmit data as JSON, or send no response body at all.)\n + \"view\"     (render and respond with a view; exit output will be provided as view locals)\n + \"redirect\" (redirect to the URL returned as the exit output)\n \n <!-- + \"error\"    (use `res.serverError()` to send the appropriate default error response, such as an error page or a JSON message with a 500 status code.  Uses your project's configured responses from `api/responses/`, if applicable.) -->\n\n**statusCode** is the status code to respond with.  (This works just like [status codes in Sails/Node](http://sailsjs.org/documentation/reference/response-res/res-status)).\n\n**viewTemplatePath** is the relative path (from the `views/` directory) of the view to render.  It is only relevant if `responseType` is set to \"view\". (This works just like [views in Sails/Express](http://sailsjs.org/documentation/concepts/views)).\n \n> If any of the above are not set explicitly, they will fall back to reasonable defaults (based on available information).\n> \n> For example, if a non-success exit is set up to serve a view, then it will use the 200 response code.\n> But if a non-success exit has no explicit response type configured (meaning it will respond with plain text,\n> JSON-encoded data, or with no data and just a status code), then machine-as-action will default to using\n> the 500 status code.  Similarly, in the same same scenario, but with `responseType: 'redirect'`, the status\n> code will default to 302.  The success exit always has a default status code of 200, unless it is also\n> `responseType: 'redirect'` (in which case it defaults to 302.)\n\n\n\n\n#### File uploads\n\nYou can use the special `files` option to map a file parameter containing an incoming Skipper upstream to a machine input:\n\n\n```js\nvar asAction = require('machine-as-action');\n\n// WeatherController.js\nmodule.exports = {\n\n\n  uploadPhoto: asAction({\n    \n\n    files: ['photo']\n    \n\n    inputs: {\n\n      photo: {\n        example: '===',\n        required: true\n      }\n\n    },\n\n\n    fn: function (inputs, exits){\n      inputs.photo.upload(function (err, uploadedFiles){\n        if (err) return exits.error(err);\n        exits.success();\n      });\n    }\n\n\n  })\n\n\n};\n```\n\n\n## Available Options\n\nAside from the [normal properties that go into a Node Machine definition](http://node-machine.org/spec), the following additional options are supported:\n\n| Option                     | Type            | Description                                            |\n|:---------------------------|-----------------|:-------------------------------------------------------|\n| `files`                    | ((array?))      | An array of input code names identifying inputs which expect to receive file uploads instead of text parameters. These file inputs must have `example: '==='`, but they needn't necessarily be `required`.\n| `urlWildcardSuffix`        | ((string?))     | If this action is handling a route with a wildcard suffix (e.g. `/foo/bar/*`), then specify this option as the code name of the machine input which should receive the string at runtime (i.e. the actual value of the \"*\" in the request URL).\n| `disableDevelopmentHeaders`| ((boolean?))    | If set, then do not automatically set headers w/ exit info during development.\n| `disableXExitHeader`       | ((boolean?))    | If set, then do not automatically send the `X-Exit` response header for any exit, regardless of whether this is a prod or dev environment.\n| `simulateLatency`          | ((number?))     | If set, then simulate a latency of the specified number of milliseconds (e.g. 500)\n| `logDebugOutputFn`    | ((function?))   | An optional override function to call when any output other than `undefined` is received from a void exit (i.e. an exit w/ no outputExample).  By default, machine-as-action uses `sails.log.warn()` if available, or `console.warn()` otherwise.\n\n> ##### NOTE\n>\n> + For **more details** on any of these options, see https://github.com/treelinehq/machine-as-action/blob/02ae23ef1d052dfe7fa6139ac14516c83c12fe1b/index.js#L30.\n> + Any of the options above should be provided as **top-level properties** of the `options` dictionary.\n> + `machine-as-action` also supports **response directives** that can be provided as additional properties within nested exit definitions.  They are `responseType`, `statusCode`, and `viewTemplatePath`.  See examples above for more information.\n\n\n## Extended example\n\nThis is a more detailed example, based on the simple intro example at the top of this README.\n\n```js\nvar asAction = require('machine-as-action');\nvar OpenWeather = require('machinepack-openweather');\n\n// WeatherController.js\nmodule.exports = {\n\n  traditionalReqRes: function (req, res) { /* ... */ },\n\n  getLatest: asAction(OpenWeather.getCurrentConditions),\n\n  doSomethingCustom: asAction({\n    description: 'Send a plaintext response.',\n    exits: {\n      success: {\n        outputExample: 'Some dynamic message like this.'\n      }\n    },\n    fn: function (inputs, exits) {\n      return exits.success('Hello world!');\n    }\n  }),\n\n  getForecastData: asAction({\n    description: 'Fetch data for the forecast with the specified id.',\n    inputs: {\n      id: { required: true, example: 325 }\n    },\n    exits: {\n      success: {\n        outputExample: {\n          weatherPerson: 'Joaquin',\n          days: [\n            { tempCelsius: 21, windSpeedMph: 392 }\n          ]\n        }\n      },\n      notFound: {\n        description: 'Could not find forecast with that id.',\n        statusCode: 404\n      }\n    },\n    fn: function (inputs, exits) {\n      Forecast.find({ id: inputs.id }).exec(function (err, forecastRecord) {\n        if (err) { return exits.error(err); }\n        if (!forecastRecord) { return exits.notFound(); }\n        return exits.success(forecastRecord);\n      });\n    }\n  }),\n\n  show7DayForecast: asAction({\n    description: 'Show the current 7 day forecast page.',\n    exits: {\n      success: {\n        responseType: 'view',\n        viewTemplatePath: 'pages/weather/7-day-forecast'\n      }\n    },\n    fn: function (inputs, exits) {\n      return exits.success('http://sailsjs.org');\n    }\n  }),\n\n  redirectToExternalForecastMaybe: asAction({\n    description: 'Redirect the requesting user agent to http://weather.com, or to http://omfgdogs.com.',\n    exits: {\n      success: { responseType: 'redirect' }\n    },\n    fn: function (inputs, exits) {\n      if (Math.random() > 0.5) {\n        return exits.success('http://weather.com');\n      }\n      else {\n        return exits.success('http://omfgdogs.com');\n      }\n    }\n  })\n\n};\n\n```\n\n\n\n## Bugs &nbsp; [![NPM version](https://badge.fury.io/js/machine-as-action.svg)](http://npmjs.com/package/machine-as-action)\n\nTo report a bug, [click here](http://sailsjs.com/bugs).\n\n\n## Contributing &nbsp; [![Build Status](https://travis-ci.org/treelinehq/machine-as-action.svg?branch=master)](https://travis-ci.org/treelinehq/machine-as-action)\n\nPlease observe the guidelines and conventions laid out in the [Sails project contribution guide](http://sailsjs.com/documentation/contributing) when opening issues or submitting pull requests.\n\n[![NPM](https://nodei.co/npm/machine-as-action.png?downloads=true)](http://npmjs.com/package/machine-as-action)\n\n\n## License\n\nMIT &copy; 2015-2016 Mike McNeil\n\n_Incorporated as a core part of the Sails framework in 2016._\n\nThe [Sails framework](http://sailsjs.com) is free and open-source under the [MIT License](http://sailsjs.com/license).\n","publish_time":1431969987376,"_cnpm_publish_time":1431969987376,"dist-tags":{"latest":"10.3.1"}}