Skip to content
Build JavaScript server apps using effects as data
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.vscode
example
src
test
.eslintignore
.gitignore
.npmrc
.travis.yml
LICENSE.md
README.md
package.json
pre-flight-tests

README.md

FX App

Build Status codecov npm

Build JavaScript server apps using effects as data.

Getting Started

$ npm i fxapp
const { app } = require("fxapp");

app({
  routes: () => ({
    response: {
      text: "Hello World"
    }
  })
});

http://localhost:8080

app Options

port

Default: 8080

The port on which the server will listen.

routes

Default: {}

Routes are defined as a nested object structure with some properties having special meanings. The first matching route value will be dispatched.

Example:

app({
  routes: {
    // GET /unknown/path
    _: fallbackAction,
    path: {
      some: {
        // GET /path/some
        GET: someReadAction,
        // POST /path/some
        POST: someAddAction
      },
      other: {
        // GET /path/other/123
        $id: otherAction
      }
    }
  }
});

Default Routes

The special wildcard _ route is reserved for routes that match in the absence of a more specific route. Useful for 404 and related behaviors. Sending a GET request to /unknown/path will respond with the results of fallbackAction.

HTTP Method Routes

Routes with the name of an HTTP request method will match any requests with that method. Sending a GET request to /path/some with the example route will respond with the results of someReadAction. A POST request to /path/some will respond with the results of someAddAction.

Path Params

Routes beginning with $ are reserved and define a path parameter for matching at that position. In the example above sending a GET request to /path/other/123 will respond with the results of passing {id: "123"} as the request.params to otherAction.

state

Default: {}

Optional initial global state values that are shared across all requests.

Advanced: customFx

Advanced: httpApi

Advanced: serverRuntime

State Shape

{
  request: {
    method: "GET",
    url: "/path/other/123?param=value&multiple=1&multiple=2",
    path: "/path/other/123",
    query: { param: "value", multiple: ["1", "2"] },
    params: { id: "123" },
    headers: {
      Host: "localhost:8080"
    }
  },
  response: {
    statusCode: 200,
    headers: { Server: "fxapp" },
    text: "Hello World"
  }
}

request

Normalized data parsed from the HTTP request that is currently being processed.

request.method

Examples: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH

The HTTP request method used to make the request.

request.url

The full request URL, including query parameters.

request.path

The request path, omitting query parameters.

request.query

An object containing the request query parameters. Multiple instances of the same parameter are stored as an array.

request.params

An object containing path parameters from the router.

request.headers

An object containing all HTTP request headers.

request.body

The contents of the request body. Respects the Content-Length header.

request.jsonBody

This will be set if the Content-Type of the request is application/json and the body content is valid JSON.

response

Data representing the HTTP response that will be sent to the client once all FX are done running.

response.statusCode

Default: 200

The HTTP status code to send in the response.

response.headers

The HTTP response headers to send.

response.custom

Skip the default logic for sending the response body. Make sure you provide customFx to handle this response or the request will hang for the client.

response.json

The HTTP response body that will be sent as application/json. Value will be formatted using JSON.stringify.

response.html

The HTTP response body that will be sent as text/html.

response.filePath

The HTTP response will pipe the contents of the file at the given path. Never pass user-provided data for this as that would introduce a vulnerability for arbitrary disk access. You may need to add response.contentType in order for the client to interpret the response correctly.

response.text

The HTTP response body that will be sent as text/plain unless a value is passed for response.contentType.

Dispatchable Types

StateUpdate = function(state: Object) => newState: Object

ReservedProps = {
  concurrent: boolean? = false,
  after: boolean? = false,
  cancel: boolean? = false
}

FX = {
  run: ({
    dispatch: function(Dispatchable),
    serverRequest: IncomingMessage,
    serverResponse: ServerResponse,
    ...ReservedProps,
    // Additional props
  }) => Promise? | undefined,
  ...ReservedProps,
  // Additional props
}

Dispatchable = StateUpdate | FX | [Dispatchable]

State Mapping Function state => newState

Perform an immutable state update by receiving the current state as a parameter and returning the new state. Automatically shallow merges root properties in addition to one level under request and response.

FX

FX as data are represented with an object containing a run function and additional properties that will be passed to that function.

The run function returns a Promise if the effect is async. Async FX are considered still running until resolved or rejected. Otherwise FX are considered sync and done once the run function returns.

Some props are reserved and have special meaning:

concurrent

Default: false

Used for running multiple FX in parallel where the results are unrelated. These FX will take priority and must all complete before running any nonconcurrent FX.

after

Default: false

Run FX after all others are complete. Use this for logging, cleanup, or providing custom response-sending logic.

cancel

Default: false

Cancel all other FX immediately. Cancelled FX are no longer able to dispatch. FX already dispatched with after will still be run to allow for the response to be sent. Use this to enforce response timeouts or for handling errors.

serverRequest

The internal http.IncomingMessage used by the Node HTTP server implementation. Allows for FX to interact with the request object to get additional data.

serverResponse

The internal http.ServerResponse used by the Node HTTP server implementation. Allows for FX to send other types of responses.

Arrays

A batch of state mapping functions and/or FX may be dispatched by wrapping them in an array.

License

FX App is MIT licensed. See LICENSE.

You can’t perform that action at this time.