Skip to content

HTTP – API

Bartosz Łaniewski edited this page Mar 24, 2018 · 3 revisions

API

new Server(config)

Each Server instance is a Proxy which defines custom behaviors for fundamental operations such as "magic" setters and getters. It allows us to reflect all custom properties to a dependency injector which keeps fundamental object safe and immutable. Gives another layer of abstraction for data.

  • Setters are used to prevent developers from overriding server internals. Additionally, custom-defined properties will be added to an internal Map object which serves as Service Location of services and it's itself a container for them.
  • Getters retrieve those properties from the Map object by key, if such key doesn't exist in server internals. You should avoid to access server internals manually, unless you know what are you doing.

.setEngine(framework)

Sets engine for our server. Each engine must implement methods described in EngineInterface.

.setRouter(framework)

Sets router for our server. Each router must implement methods described in RouterInterface.

.addHandler(name, callback)

Adds a handler. A handler is describes by its name which is used to identify specific kind of files and a callback which handles those files. For example .addHandler("Router", …) will be applied to all classes with suffix -Router (ex. class FooRouter).

.run(port, callback)

Listens on a given port.

.use(middleware)

Mounts the specified middleware function or functions.

.import(path)

Imports, initialises and saves a given resource. Each resource is handled by it individual handler. Resources are recognized based on their name, so a *Middleware will be interpreted as a middleware and a *Router will be interpreted as a router.

Examples

const app = new Server(config);

app.setEngine(new Koa());
app.setRouter(new Router());

app.addHandler("Middleware", Server.middlewareHandler);
app.addHandler("Router", Server.routerHandler);
app.addHandler("default", Server.defaultHandler);

app.import("./UserRoutes");
app.import("./BlogRoutes");

app.run();

Clone this wiki locally