Skip to content

Commit

Permalink
upload
Browse files Browse the repository at this point in the history
  • Loading branch information
dragonwocky committed Feb 6, 2022
0 parents commit 7a1e906
Show file tree
Hide file tree
Showing 12 changed files with 680 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"deno.enable": true,
"deno.lint": true,
"deno.unstable": true
}
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## v0.1.0 (2022-02-06)

Initial release.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) dragonwocky <[email protected]> (https://dragonwocky.me)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# 🐍 nadder

**nadder** is a HTTP and WebSocket router for Deno,
built primarily for personal use.

- It can handle **any request method**.
- It matches routes based on the
**[URL Pattern API](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)**.
- It includes a **PostgreSQL** connection wrapper.
- It includes in-memory or PostgresSQL **session storage** with garbage collection and expiry.
- It includes a **[Windi CSS](https://windicss.org/) processor**.
- It includes a **JSX transformer** (without React).
- It provides utilities for responding to requests with
**static files, HTML, JSON, or HTTP status codes**.
- It provides simple **reading and manipulation of cookies**.

## Quick start

```tsx
/**
* @jsx h
* @jsxFrag jsxFrag
*/

import 'https://deno.land/x/dotenv/load.ts';

import {
h,
jsxFrag,
jsxResponse,
postgresConnection,
postgresSession,
route,
serve,
windiInstance,
} from 'https://deno.land/x/nadder/mod.ts';

const postgres = postgresConnection({
password: Deno.env.get('POSTGRES_PWD'),
hostname: Deno.env.get('POSTGRES_HOST'),
}),
session = await postgresSession(postgres);

route('GET', '/{index.html}?', async (ctx) => {
const count = (((await session.get(ctx, 'count')) as number) ?? -1) + 1;
await session.set(ctx, 'count', count);

const { tw, sheet } = windiInstance();
jsxResponse(
ctx,
<>
<p class={tw`font-bold m-4`}>
Page load count: <span class={tw`text-green-600`}>{count}</span>
</p>
{sheet()}
</>
);
});

serve();
```

All other features are also made available as exports of the `mod.ts` file
(inc. e.g. registering WebSocket listeners, sending JSON responses, serving files
and initialising in-memory session storage).

For convenience, the following dependencies are re-exported:

- `setCookie`, `deleteCookie`, `Cookie`, `HTTPStatus` and `HTTPStatusText` from [`std/http`](https://deno.land/std/http).
- `contentType` from [`https://deno.land/x/media_types`](https://deno.land/x/media_types)

---

Changes to this project are recorded in the [CHANGELOG](CHANGELOG.md).

This project is licensed under the [MIT License](LICENSE).

To support future development of this project, please consider
[sponsoring the author](https://github.com/sponsors/dragonwocky).
23 changes: 23 additions & 0 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export * as path from "https://deno.land/[email protected]/path/mod.ts";
export { readableStreamFromReader } from "https://deno.land/[email protected]/streams/mod.ts";

export { serve as stdServe } from "https://deno.land/[email protected]/http/server.ts";

export type { Cookie } from "https://deno.land/[email protected]/http/cookie.ts";
export {
deleteCookie,
getCookies,
setCookie,
} from "https://deno.land/[email protected]/http/cookie.ts";

export {
Status as HTTPStatus,
STATUS_TEXT as HTTPStatusText,
} from "https://deno.land/[email protected]/http/http_status.ts";

export { contentType } from "https://deno.land/x/[email protected]/mod.ts";

export { default as WindiProcessor } from "https://esm.sh/[email protected]";
export { StyleSheet } from "https://esm.sh/[email protected]/utils/style";

export * as postgres from "https://deno.land/x/[email protected]/mod.ts";
27 changes: 27 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* nadder
* (c) 2022 dragonwocky <[email protected]> (https://dragonwocky.me/)
* (https://github.com/dragonwocky/nadder) under the MIT license
*/

export { postgresConnection } from "./postgres.ts";
export {
fileResponse,
htmlResponse,
jsonResponse,
jsxResponse,
statusResponse,
} from "./response.ts";
export { route, serve, ws } from "./server.ts";
export { memorySession, postgresSession } from "./session.ts";
export { h, jsxFrag, jsxToString, windiInstance } from "./ssr.tsx";
export {
contentType,
deleteCookie,
HTTPStatus,
HTTPStatusText,
setCookie,
} from "./deps.ts";

export type { HTTPMethod, RouteContext, SocketContext } from "./server.ts";
export type { Cookie } from "./deps.ts";
36 changes: 36 additions & 0 deletions postgres.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* nadder
* (c) 2022 dragonwocky <[email protected]> (https://dragonwocky.me/)
* (https://github.com/dragonwocky/nadder) under the MIT license
*/

import { postgres } from "./deps.ts";

export const postgresConnection = ({
user = "postgres",
password = Deno.env.get("POSTGRES_PWD"),
hostname = Deno.env.get("POSTGRES_HOST"),
port = "6543",
database = "postgres",
} = {}) => {
// creates lazy/on-demand connections
// for concurrent query execution handling
// = more performant and reusable than a normal client
const config = { user, password, hostname, port, database },
pool = new postgres.Pool(config, 3, true),
query = async (...args: unknown[]): Promise<unknown | Error> => {
const connection = await pool.connect();
try {
// @ts-ignore pass all args
const res = await connection.queryObject(...args);
return res;
} catch (err) {
console.error(err);
return err;
} finally {
// returns connection to the pool for reuse
connection.release();
}
};
return query;
};
50 changes: 50 additions & 0 deletions response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* nadder
* (c) 2022 dragonwocky <[email protected]> (https://dragonwocky.me/)
* (https://github.com/dragonwocky/nadder) under the MIT license
*/

import { RouteContext } from "./server.ts";
import { jsxToString } from "./ssr.tsx";
import {
contentType,
HTTPStatus,
HTTPStatusText,
path,
readableStreamFromReader,
} from "./deps.ts";

export const jsonResponse = (ctx: RouteContext, data: unknown) => {
if (data instanceof Map || data instanceof Set) data = [...data];
ctx.res.body = JSON.stringify(data, null, 2);
ctx.res.status = HTTPStatus.OK;
ctx.res.headers.set("content-type", contentType("json")!);
};

export const statusResponse = (ctx: RouteContext, status: number) => {
ctx.res.body = `${status} ${HTTPStatusText.get(status) ?? ""}`;
ctx.res.status = status;
};

export const htmlResponse = (ctx: RouteContext, html: string) => {
ctx.res.body = html;
ctx.res.status = HTTPStatus.OK;
ctx.res.headers.set("content-type", contentType("html")!);
};

export const jsxResponse = (ctx: RouteContext, $: JSX.Element) => {
htmlResponse(ctx, `<!DOCTYPE html>${jsxToString($)}`);
};

export const fileResponse = async (ctx: RouteContext, filepath: string) => {
try {
const stat = await Deno.stat(filepath);
if (stat.isDirectory) filepath = path.join(filepath, "index.html");
const file = await Deno.open(filepath, { read: true });
ctx.res.body = readableStreamFromReader(file);
ctx.res.headers.set("content-type", contentType(path.basename(filepath))!);
ctx.res.status = HTTPStatus.OK;
} catch {
statusResponse(ctx, HTTPStatus.NotFound);
}
};
Loading

0 comments on commit 7a1e906

Please sign in to comment.