A small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity

Overview

Wren

wren: a small, but powerful HTTP library for Deno & Deno Deploy

Wren is a small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity.

import { serve } from "wren/mod.ts";
import { GET, POST } from "wren/route.ts";
import * as Response from 'wren/response.ts';

const routes = [
  GET('/', () => Response.OK('Hello, Wren')),
  POST('/form-post', ({ params }) => 
    Response.Created(`Received: ${JSON.stringify(params)}`)),
];

serve(routes, { port: 3000 });

Features

Aliases for HTTP Responses

Wren adds aliases for HTTP responses so that you can not only write them faster (less characters to write), but you use the actual HTTP status names and not the codes.

// with Wren

import * as Response from 'wren/response.ts'; // don't forget to configure the import map for this to work

// ...somewhere in your handler (type: `Handler`)

return Response.OK('Your Body');
return Response.InternalServerError('Your Body');
return Response.MethodNotAllowed();

// without Wren

import { Status } from "http/http_status.ts"; // Deno's HTTP module

return new Response('Your body', { status: 200 });
return new Response('Your body', { status: Status.OK });

return new Response('Something bad ', { status: 500 });
return new Response('Something bad ', { status: Status.InternalServerError });

return new Response('', { status: 405 });
return new Response('', { status: Status.MethodNotAllowed });

// etc...

Serialization of Plain Objects into JSON Responses

In addition to having less to write when using Wren's aliases for HTTP responses, you can also pass a plain JavaScript object directly to these alias functions, and it will be automatically serialized to a JSON response with the proper Content-Type headers (using Deno's Response.json() underneath)

return Response.OK({ source: 'XYZ', message: 'Something went wrong', code: 1234 })
return Response.Created({ message: 'Widget created successfully', code: 777 })

Typed JSON Responses

When you return plain JavaScript objects as the body of your responses, it would be great to have a way to define the shape of this data in order to avoid silly mistakes with typos or just to have a tighter interface between your API and its consumers. In Wren, responses can be optionally typed:

interface ReturnPayload {
  source: string;
  message: string;
  code: number
}

return Response.OK<ReturnPayload>({ 
  source: 'XYZ',
  message: 'Something went wrong',
  code: 1234,
}); // this is OK

return Response.OK<ReturnPayload>({
  surce: 'XYZ', // squiggly lines for `surce` + autocomplete in your editor
  message: 'Something went wrong',
  code: 1234,
}); 

Router

Wren comes with a simple router built around the URLPattern API. It provides two methods: (1) add to register a handler for a specific HTTP method and pathname, and (2) find to retrieve a handler for given HTTP method and Request's URL.

Wren builds on top of this Router to provide the Routing object in a form of a Middleware (more about middlewares in Wren below).

With Routing you can define your routing as an array of (potentially nested) Routes.

import { serve } from "http/server.ts"; // Deno's HTTP server
import { GET, POST } from "wren/route.ts";
import { Routing } from "wren/routing.ts";
import * as Response from 'wren/response.ts';

const routes = [
  GET('/', () => Response.OK('Hello, Wren')),
  GET('/hello', () => Response.Accepted('Hello, again Wren')),
  POST('/form-post', ({ params }) =>
    Response.Created(`Received: ${JSON.stringify(params)}`)),
]

const routing = Routing(routes);
serve(routing, { port: 3000 });

Instead of using the serve function from Deno's standard library, you can swap it with the serve provided by Wren to pass the routes array directly.

import { serve } from "wren/mod.ts";
import { GET, POST } from "wren/route.ts";
import * as Response from 'wren/response.ts';

const routes = [
  ...
];

serve(routes, { port: 3000 });

Parsing of Request's Body

Wren automatically parses the URL and the body (based on its Content-Type) of the incoming request to combine the search params, body params and path params into the additional params field of the request.

Quick Reminder:

  • search params come from the URL and are defined after the ? sign with each separated by the & sign; e.g. http://example.com?foo=1&bar=baz will be transformed into { foo: 1, bar: 'baz' } in Wren,
  • body params are the fields sent in the request body and can come from the form submissions, JSON requests or as fields in multipart,
  • path params are segments of the pathname designated as dynamic e.g. /something/:name will be transformed into { name: 'wren' } in Wren when invoked as /something/wren,

For convenience, Wren combines all those params into a single, readily available object.

In addition to that, when you sent multipart requests, Wren also provides the uploaded files as the additional files field of the request.

const handler: Handler = (request) => {
  const { params, files } = request;

  for (const file of files) {
    // iterate over files to process them or to save them on disk
  }

  return Response.OK(params)
}

The shape for both params and files is provided as an intersection type RequestExtension not to obscure the built-in Deno's Request as defined in the Fetch API.

Composable Middlewares

In Wren middlewares are functions that take a handler as input and return a handler as output - as simple as that! :)

Thus, the Middleware type is defined as:

type Middleware = (handler: Handler) => Handler

(TBD soon. Check the source code or examples in the meantime)

TypeScript Types

Middleware

TBD

Pipeline

Pipeline represents composition of a series of middlewares over a handler; thus:

type Pipeline = [...Middleware[], Handler];

A pipeline is folded or composed in a single handler by applying each middleware onto another and finally on the last handler.

In Wren, middlewares can be defined globally (similar to the .use method in Express), but also locally, i.e. per particular route, which makes it much more flexible in practice than alternatives.

TDB

RequestExtension

RequestExtension defines params and files that are automatically extracted from the incoming request. This type is defined as an intersection type to the built-in Request type so it's less intrusive.

type Handler = (request: Request & RequestExtension, connInfo: ConnInfo) => Response | Promise<Response>;
You might also like...

⚗️Nitro provides a powerful toolchain and a runtime framework from the UnJS ecosystem to build and deploy any JavaScript server, anywhere

⚗️Nitro provides a powerful toolchain and a runtime framework from the UnJS ecosystem to build and deploy any JavaScript server, anywhere

Jan 5, 2023

📡Usagi-http-interaction: A library for interacting with Http Interaction API

📡 - A library for interacting with Http Interaction API (API for receiving interactions.)

Oct 24, 2022

Simple and Extensible Markdown Parser for Svelte, however its simplicity can be extended to any framework.

svelte-simple-markdown This is a fork of Simple-Markdown, modified to target Svelte, however due to separating the parsing and outputting steps, it ca

May 22, 2022

A lightweight @discord client mod focused on simplicity and performance.

Replugged Maintained fork of powercord - a lightweight @discord client mod focused on simplicity and performance. Installation/Uninstallation See the

Jan 9, 2023

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Getting Started with Jest Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Built With Javascript Linters Jest Live Demo N

Dec 20, 2022

A simple but powerful tweening / animation library for Javascript. Part of the CreateJS suite of libraries.

TweenJS TweenJS is a simple tweening library for use in Javascript. It was developed to integrate well with the EaselJS library, but is not dependent

Jan 3, 2023

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

HTTPFY curently in beta so you may see problems. Please open a Issue on GitHub and report them! A Incredible fast and Powerful HTTP toolkit Report Bug

Dec 22, 2022

A minimal yet powerful HTTP client/API testing tool made for speed.

A minimal yet powerful HTTP client/API testing tool made for speed.

req req is a lightweight, minimal yet powerful HTTP client slash API testing tool designed for speed. Contents Features Installation Documentation Con

Aug 29, 2022

A server side rendering framework for Deno CLI and Deploy. 🦟 🦕

nat A server side rendering framework for Deno CLI and Deploy. Incorporating acorn, nano-jsx, and twind, it provides the tooling to provide a server c

Nov 17, 2022
Comments
Owner
Jakub Neander
Occasional JavaScript programmer. On a quest for the Holy Grail of Programming. But first I need to understand Self.
Jakub Neander
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs

A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs with no dependencies. It also has a collection of useful middlewares: log file, serve static, CORS, session, rate limit, token, body parsers, redirect, proxy and handle upload. In "README" there are examples of all the resources. Faster's ideology is: all you need is an optimized middleware manager, all other functionality is middleware.

Henrique Emanoel Viana 19 Dec 28, 2022
Node JS/TypeScript module that allows you to work with the site enka.network adding localization and convenience.

enkaNetwork Node JS/TypeScript module that allows you to work with the site enka.network adding localization and convenience. examples • structure ??

kravets 12 Nov 18, 2022
This is a simple boilerplate for a Deno website, deployed with Deno Deploy.

Simple Deno Website Boilerplate This is a simple website boilerplate built using Deno and deployed using Deno Deploy. Demo at simple-deno-website-boil

Bruno Bernardino 15 Dec 3, 2022
TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy

Atlas SDK atlas_sdk is a TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy Links Docs Import Replace LATEST_VERSION with current latest versi

Erfan Safari 20 Dec 26, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
To Do list is a small but useful project to make list app , you can add tasks delete tasks and modify tasks, the project built using HTML, CSS, JavaScript

Project Name The To-Do-List app description this is a project in the second week of the second module in microverse. its a useful to do list that save

Alzubair Alqaraghuli 5 Jul 25, 2022
A small javascript DOM manipulation library based on Jquery's syntax. Acts as a small utility library with the most common functions.

Quantdom JS Quantdom is a very small (about 600 bytes when ran through terser & gzipped) dom danipulation library that uuses a Jquery like syntax and

Sean McQuaid 7 Aug 16, 2022