2.3.1 • Published 3 years ago

shiorack v2.3.1

Weekly downloads
3
License
MIT
Repository
github
Last release
3 years ago

shiorack.js

npm npm license npm download total npm download by month

Dependency Status devDependency Status build codecov.io

Middleware based Ukagaka SHIORI subsystem interface builder inspired by rack and koa

Install

npm install shiorack

Usage

/// <reference types="node" />

import { NoContent, OK, wrapRequestCallback } from "shiori-request-helper";
import * as ShioriJK from "shiorijk";
import { ShioriBuilder } from "shiorack";

interface HeadersState {
  defaultHeaders: { [name: string]: string };
}

const builder = new ShioriBuilder()
  .use({
    state: {} as { dirpath: string },
    // set dirpath
    load: (ctx, next) => {
      ctx.state.dirpath = ctx.dirpath;

      return next();
    },
    // exit
    unload: async (_ctx, next) => {
      await next();
      process.exit();
    },
  })
  .use({
    state: {
      defaultHeaders: { Charset: "UTF-8" },
    } as HeadersState,
    // error handler
    request: async (ctx, next) => {
      try {
        return await next();
      } catch (error) {
        return new ShioriJK.Message.Response({
          status_line: { code: 400, version: "3.0" },
          headers: {
            ...ctx.state.defaultHeaders,
            "X-Shiori-Error": error.message.replace(/\r?\n/g, "\\n"),
          },
        });
      }
    },
  })
  // ignore OnTranslate
  .useRequest((ctx, next) => {
    if (ctx.request.headers.ID === "OnTranslate") {
      return new ShioriJK.Message.Response({
        status_line: { code: 400, version: "3.0" },
        headers: {
          Charset: "UTF-8",
        },
      });
    }

    return next();
  })
  // set ghost name to sender
  .useRequest((ctx, next) => {
    if (ctx.request.headers.ID === "ownerghostname") {
      const sender = ctx.request.headers.Reference(0);
      if (typeof sender === "string" && sender.length) {
        ctx.state.defaultHeaders.Sender = sender;
        ctx.state.sender = sender;
      }
    }

    return next();
  }, {} as { sender: string });

// process request events
const requestCallback = wrapRequestCallback(
  (request: ShioriJK.Message.Request) => {
    switch (request.headers.ID) {
      case "OnBoot":
        return OK("\\h\\s[0]hello.\\e");
      default:
        return NoContent();
    }
  },
  builder.state.defaultHeaders
);

const builder2 = builder.useRequest((ctx) => requestCallback(ctx.request));

export default builder2.build(); // build SHIORI interface
shiolinkjs ./myShiori.js

API Document

https://narazaka.github.io/shiorack.js/

License

This is released under MIT License.

2.3.1

3 years ago

2.3.0

3 years ago

2.2.2

3 years ago

2.2.1

3 years ago

2.2.0

6 years ago

2.1.2

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.0

6 years ago

1.0.0

6 years ago