Skip to content

Very simple handler for converting node:http's IncomingMessage object into a Fetch API Request

License

Notifications You must be signed in to change notification settings

0aoq/http-to-fetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

http-to-fetch

Very simple handler for converting node:http's IncomingMessage object into a Fetch API Request

Usage

npm install http-to-fetch

After starting a server using node:http, listen for requests and convert the objects. Example:

// (typescript)
import http from "node:http";

http.createServer((request, response) => {
    // create request and return 200 response
    const req = new Request();
    req.translate(request, response);

    // the HTTPResponse object will automatically close the request!
    new HTTPResponse(
        `Hi mom!`, // body
        {
            // options
            status: 200,
            headers: new Headers({
                "Content-Type": "text/plain",
            }),
        },
        req // request
    );
}).listen(8080);

Usage (with PluginAPI)

This library also includes a "Plugin API" that makes the whole process much more like the the native web Fetch API.

Using a basic loader (or the one from /example), just listen and handle the request.

// (typescript)
import loader from "./loader.js";

// start server
loader.start(8080);

// bind endpoint
loader.bind({
    endpoint: "/", // serve everything on the root endpoint (/)
    fetch: (Request, Response) => {
        return new Response(
            "Hello, world!", // body
            {
                // options
                status: 200,
                headers: new loader.Headers({
                    "Content-Type": "text/plain",
                    "Hi-Mom": "It works!",
                }),
            }
        );
    },
});

This loader uses the Plugin.registerEndpoint to register an endpoint for the endpoint you defined.

// (typescript)
// from: loader.ts
// ...
export function bindEndpoint(params: { endpoint: string; fetch: fetch }) {
    // create plugin client
    const pluginClient = new Plugin();

    // update plugin client bindings
    pluginClient.bindOnRegEndpoint((endpoint: string, fetch: fetch) => {
        endpointList[endpoint] = fetch;
        endpointList[`${endpoint}/`] = fetch; // account for trailing slash
    });

    // bind endpoint
    pluginClient.registerEndpoint(params.endpoint, params.fetch);
}
// ...

loader.bind just calls loader.bindEndpoint

// (typescript)
// from: loader.ts
// ...
export default {
    bind: bindEndpoint,
    // ...

It is recommended that you just use the example loader and extend it.

About

Very simple handler for converting node:http's IncomingMessage object into a Fetch API Request

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published