npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-negotiate-middleware

v0.0.2

Published

negotiation middleware for express

Downloads

61

Readme

express-negotiate-middleware

This middleware allows client to negotiate responses based on the accept or content-type headers allowing a single route to return multi-formats of data.

Features

  • clients to accept multiple responses application/xhtml+xml;q=0.9,*/*;q=0.7,application/xml;q=0.8,text/html;q=1
  • client to state which response they perfer with relative quality factor
  • default handlers for fallback responses

Project Status

npm (tag)

Installation

Requirements

  • Node Version: 16+ (may work on older versions but not tested)
  • Dependencies are listed in package.json

Install dependencies

npm install

Linting

Run the Static analiser:

npm run lint

Correct issues which can be automatically fixed:

npm run lint:fix

Testing

Full test suite:

npm test

Examples

Basic Example

In this example the server will have the abilty to return both html and JSON. The client will able to negation which gets returned.

Server

import express, { Request, Response } from 'express';
import { negotiate, NotAcceptable } from 'express-negotiate-middleware';

const jsonHandler = (_request: Request, response: Response): void => {
  response.json({ message: 'hello world' });
};

const htmlHandler = (_request: Request, response: Response): void => {
  response.send('<h1>hello world</h1>');
};

const application = express();

application.get('/', negotiate({ 'application/json': jsonHandler, 'text/html': htmlHandler }));

application.listen(8080);

Client


// ask the server for json
const jsonData = await fetch('http://localhost:8080/', {
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
});
// ask the server for html
const htmlData = await fetch('http://localhost:8080/', {
    headers: {
      'Accept': 'text/html',
      'Content-Type': 'text/html'
    },
});

// prefer json by using q parameter
// q is usally between 0-1 higher numbers mean return this type first

const jsonData = await fetch('http://localhost:8080/', {
    headers: {
      'Accept': 'application/json;q=1,text/html',
    },
});

Default handlers

You can set a default handler that all requests fall into should a negatiation fails

application.get('/', negotiate({ 
    'application/json': jsonHandler, 
    'text/html': htmlHandler, 
    // if negation fails return json
    default: jsonHanlder 
}));

If there is no default handler then failed negatiations will throw NotAcceptable error

Handling errors

Creating a error handling middleware allows for all errors to be passed to next(error) and be handled in a single location

import express, { Request, Response } from 'express';
import { negotiate, NotAcceptable } from 'express-negotiate-middleware';

const jsonHandler = (_request: Request, response: Response): void => {
  response.json({ message: 'hello world' });
};

const htmlHandler = (_request: Request, response: Response): void => {
  response.send('<h1>hello world</h1>');
};

const application = express();

application.get('/', negotiate({ 'application/json': jsonHandler, 'text/html': htmlHandler }));

application.use((error: unknown, _request: Request, response: Response) => {
  if (error instanceof NotAcceptable) {
    response.status(error.statusCode).json({ error: error.message });
  } else {
    response.status(500).json(error);
  }
});

application.listen(8080);