Code Monkey home page Code Monkey logo

fluture-express's Introduction

Fluture Express

NPM Version Dependencies Code Coverage

Create Express middleware using Futures from Fluture.

Allows for the definition of pure functions to be used as Express middleware. This has benefits for testing and developer sanity. Another benefit of this particular approach, where every middleware is wrapped individually, is that it plays nicely with existing Express middleware, and they can be used interchangably.

Usage

Node

$ npm install --save fluture-express

On Node 12 and up, this module can be loaded directly with import or require. On Node versions below 12, require or the esm-loader can be used.

Deno and Modern Browsers

You can load the EcmaScript module from various content delivery networks:

Usage Example

// index.js

const {dispatcher} = require ('fluture-express');
const app = require ('express') ();
const dispatch = dispatcher ('./actions');

app.use (dispatch ('welcome'));
app.listen (3000);
// actions/welcome.js

const {Json} = require ('fluture-express');
const Future = require ('fluture');

module.exports = locals => req => Future.go (function* () {
  const user = yield locals.database.find ('sessions', locals.session.id);
  return withStatus (418) (Json ({welcome: user.name}));
});

For a more in-depth example, see the example directory.

Documentation

Pseudo types

Req

The Express Request object.

Res a

The Express Response object with a locals property of type a.

The Response type

Fluture-Express mutates the response object for you, based on a specification of what the response should be. This specification is captured by the Response sum-type.

The Response sum type encoded with daggy. You probably don't need to use this directly.

data Response a b = Respond (Array Head) (Body a)
                  | Next b

The Head sum type encoded with daggy. You probably don't need to use this directly.

data Head = Status Number
          | Type String
          | Location String
          | Links (StrMap String)
          | Cookie String String Object
          | ClearCookie String Object
          | HeaderPart String String
          | Header String String

The Body sum type encoded with daggy. You probably don't need to use this directly.

data Body a = None
            | Send Any
            | Json JsonValue
            | Stream (Future a Readable)
            | Render String Object

Creates a streamed response given a mime type and a Future that produces a Readable Stream when consumed. The Future is expected to produce a new Stream every time it's consumed, or if it can't, reject with a value that your Express error handler can handle.

Uses a Content-Type of application/octet-stream unless overridden by withType, withHeader, or withoutHeader.

Indicates a textual response.

Uses a Content-Type of text/plain unless overridden by withType, withHeader, or withoutHeader.

Indicates a JSON response.

Uses a Content-Type of application/json unless overridden by withType, withHeader.

Indicates a response to be rendered using a template. The first argument is the path to the template file, and the second is the data to inject into the template. This uses Express' render method under the hood, so you can configure it globally with app.set ('view engine', engine) and app.set ('views', path).

Indicates a redirection. The first argument will be the response status code, and the second will be the value of the Location header.

Unless overridden by withStatus, the status code will be set to 301 (Moved Permanently).

Indicates an empty response. The response status will be set to 204, and no response body or Content-Type header will be sent.

Indicates that this middleware does not form a response. The supplied value will be assigned to res.locals and the next middleware will be called.

Configure the status code by setting up a call to res.status.

Configure the Content-Type by setting up a call to res.type.

Configure the Location header by setting up a call to res.location.

Configure the Link header by setting up a call to res.links.

Configure the Set-Cookie header by setting up a call to res.cookie.

Configure the Set-Cookie header by setting up a call to res.clearCookie.

Append to a header by setting up a call to res.append.

Configure a header by setting up a call to res.set.

Removes a header from the Response. Also removes headers that would be set by functions like withType. For example:

> withoutHeader ('Content-Type') (withType ('json') (Empty))
Empty

Middleware creation utilities

Converts an action to an Express middleware.

Takes a function that returns a Future of a Response, and returns an Express middleware that uses the returned structure to make the appropriate mutations to the res.

If the Future rejects, the rejection reason is passed into next for further error handling with Express.

Creates middleware that uses the export from the given file in the given directory as an "action".

It takes the file in two steps for convenience. You are encouraged to use the first parameter to set up a sub-directory where all your actions live.

The exported value should be a function of the same signature as given to middleware.

fluture-express's People

Contributors

avaq avatar dicearr avatar greenkeeper[bot] avatar voxbono avatar wuweiss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

fluture-express's Issues

An in-range update of sinon is breaking the build 🚨

☝️ Greenkeeper’s updated Terms of Service will come into effect on April 6th, 2018.

Version 4.4.7 of sinon was just published.

Branch Build failing 🚨
Dependency sinon
Current Version 4.4.6
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 7 commits.

  • e060fe9 Update docs/changelog.md and set new release id in docs/_config.yml
  • e9fce06 Add release documentation for v4.4.7
  • f047838 4.4.7
  • cc91fe6 Update History.md and AUTHORS for new release
  • 9fb8577 Emojify the support message :heart:
  • a87ef85 Use existing mini-lib for coloring
  • 1f33fe5 Reduce noisy NPM output from postinstall script

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Using fluture/test/assertions.js with Json is never reference-equal

Using fluture/test/assertions.js with Json is never reference-equal when Json is imported from a commonjs module and esm module and compared with equivalence.

When using Json from 'fluture-express', if you test subject is a commonjs module, then the value in the Json object is not reference-equal and tests with equivalence from 'fluture/test/assertions.js' will fail even though the tests should pass.

Error:
	resolve ({"body": {"data": {"foo": "bar"}}, "head": []}) :: Future({ <resolved> {"body": {"data": {"foo": "bar"}}, "head": []} })
is not equivalent to:
	resolve ({"body": {"data": {"foo": "bar"}}, "head": []}) :: Future({ <resolved> {"body": {"data": {"foo": "bar"}}, "head": []} })

The inner values are not equal: Values have same structure but are not reference-equal

Example of error message when Json is not imported via esm.

However, note that it does not matter if your test data is from a commonjs module or EcmaScript module (esm).

A thorough run down is in the https://github.com/dotnetCarpenter/fluture-test-gotcha repository.

It boils down to strictEqual and show from 'sanctuary-show' not playing nice together. I guess that the output of show (a) changes depending on module format. But that is a guess.

// always success
deepStrictEqual (Json (data1), Json (data1));
deepStrictEqual (Json (data2), Json (data2));
// always failure
strictEqual (Json (data1), Json (data1));
strictEqual (Json (data2), Json (data2));

strictEqual.mjs and strictEqual.js

An in-range update of sanctuary-scripts is breaking the build 🚨

Version 1.5.0 of sanctuary-scripts was just published.

Branch Build failing 🚨
Dependency sanctuary-scripts
Current Version 1.4.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sanctuary-scripts is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 3 commits.

  • ce8733d Version 1.5.0
  • 6fd7771 Merge pull request #13 from sanctuary-js/davidchambers/lint-readme
  • 468b5ef lint-readme: lint doctests and other code blocks

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of sinon is breaking the build 🚨

Version 5.0.9 of sinon was just published.

Branch Build failing 🚨
Dependency sinon
Current Version 5.0.8
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 5 commits.

  • 86b930c Update docs/changelog.md and set new release id in docs/_config.yml
  • 033aa60 Add release documentation for v5.0.9
  • 3321085 5.0.9
  • 9f321d5 Update History.md and AUTHORS for new release
  • e862196 Upgrade @std/esm to esm.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of sinon is breaking the build 🚨

Version 5.0.1 of sinon was just published.

Branch Build failing 🚨
Dependency sinon
Current Version 5.0.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 182 commits ahead by 182, behind by 30.

  • ac71bfd Fix invalid documentation for fake.yields, fake.yieldsAsync
  • beb4c6b Add release documentation for v5.0.1
  • d707712 Update docs/changelog.md and set new release id in docs/_config.yml
  • bb062a3 5.0.1
  • 5d885b2 Update History.md and AUTHORS for new release
  • c794709 Add documentation for fake().callback and fake().lastArg
  • d5cd20f Add .lastArg and .callback to fake and call
  • 01cbe61 Allow replacing non-own object properties (#1705)
  • 7e2f05a Change yields semantics to match stub behaviour
  • cf99c5a Add a failing test for #1695
  • 88e6e5f Remove deprecated spy.reset method
  • f133b6a Docs: add migration guide for v5
  • f29f918 Add replace methods
  • afec7b2 Extract isPropertyConfigurable to own file
  • 738638d Extract nextTick to own file

There are 182 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.