Plugin

A plugin is a way to decouple logic into smaller parts, defining reusable components across the server.

Defining a plugin is as simple as defining a new Teakit instance:

import { Application } from "@teakit/core";
const plugin = new Application().state("plugin-version", 1).get("/from-plugin", () => "Hi");
const app = new Application()
.use(plugin)
.get("/version", ({ store }) => store["plugin-version"])
.listen(8080);

Plugins can be registered by using use method.

Registering a plugin will combine types between the plugin and current instance, and the scope of hooks and schema get merged as well.

Separate file

Using the plugin pattern, you can define and decouple your logic into a separate file.

// plugin.ts
export const plugin = new Application().get("/from-plugin", () => "Hi");
// main.ts
import { plugin } from "./plugin";
const app = new Application().use(plugin).listen(8080);

Functional callback

You can also define a function callback to inline the plugin.

// plugin.ts
export const plugin = (app: Application) => app.get("/from-plugin", () => "Hi");
// main.ts
import { plugin } from "./plugin";
const app = new Application().use(plugin).listen(8080);

Functional callback will allow a user to access main instance values like routes, schema, store, etc.

Config

You can customize a plugin by creating a function to return callback which accepts Teakit.

import { Application } from "@teakit/core";
const plugin = <const Prefix>({ prefix = "/v1" }: { prefix: Prefix }) => new Application({ prefix }).get(`/hi`, () => "Hi");
const app = new Application()
.use(
plugin({
prefix: "/v2",
})
)
.listen(8080);

Config type will be inferred into use, generating auto completion and type strict as intend.

Plugin deduplication

By default, Teakit will register any plugin and handle type definitions which when using multiple times will results in a multiple duplication of setting value or routes.

This can be fixed by providing name and optional seeds to help Teakit identify instance duplication:

import { Application } from "@teakit/core";
const plugin = (config) =>
new Application({
name: "@teakit/plugin-name",
seed: config,
}).get(`${config.prefix}/hi`, () => "Hi");
const app = new Application()
.use(
plugin({
prefix: "/v2",
})
)
.listen(8080);

Official plugins

You can find pre-built plugins for Application at plugins.

PreviousContext