@hapipal/schmervice

中文文档
3.0.0发布于 2023/02/27MITTypeScriptCommonJS零依赖近 30 天下载 8540

A service layer for hapi

原始使用文档
文档目录5 节
  1. Installation
  2. Usage
  3. Functional style
  4. Using existing libraries as services
  5. Extras

schmervice

A service layer for hapi

Build Status Coverage Status

Lead Maintainer - Devin Ivy

Installation

npm install @hapipal/schmervice

Usage

See also the API Reference

Schmervice is intended for use with hapi v20+ and nodejs v16+ (see v2 for lower support).

Services are a nice way to organize related business logic or transactions into classes. Schmervice is a service layer designed to integrate nicely with hapi. It consists of two parts that can be used together or separately:

  1. a base Service class that integrates your service with hapi by:

    • giving it access to the relevant server and plugin options.
    • allowing you to implement async initialize() and async teardown() methods that should run when the server initializes and stops.
    • allowing you to configure certain methods as being cacheable, with all the server method configuration that you're accustomed to.
  2. a hapi plugin that allows you to register services and access them where it is most convenient, such as in route handlers. This registry respects plugin boundaries and is hierarchical, so unrelated plugins can safely register their own services without affecting each other.

const Schmervice = require('@hapipal/schmervice');
const Hapi = require('@hapi/hapi');

(async () => {

    const server = Hapi.server();

    await server.register(Schmervice);

    server.registerService(
        class MathService extends Schmervice.Service {

            add(x, y) {

                this.server.log(['math-service'], 'Adding');

                return Number(x) + Number(y);
            }

            multiply(x, y) {

                this.server.log(['math-service'], 'Multiplying');

                return Number(x) * Number(y);
            }
        }
    );

    server.route({
        method: 'get',
        path: '/add/{a}/{b}',
        handler: (request) => {

            const { a, b } = request.params;
            const { mathService } = request.services();

            return mathService.add(a, b);
        }
    });

    await server.start();

    console.log(`Start adding at ${server.info.uri}`);
})();

Functional style

Schmervice allows you to write services in a functional style in additional to the class-oriented approach shown above. server.registerService() can be passed a plain object or a factory function. Just make sure to name your service using the Schmervice.name symbol or a name property. Here's a functional adaptation of the example above:

const Schmervice = require('@hapipal/schmervice');
const Hapi = require('@hapi/hapi');

(async () => {

    const server = Hapi.server();

    await server.register(Schmervice);

    server.registerService(
        (srv) => ({
            [Schmervice.name]: 'mathService',
            add: (x, y) => {

                srv.log(['math-service'], 'Adding');

                return Number(x) + Number(y);
            },
            multiply: (x, y) => {

                srv.log(['math-service'], 'Multiplying');

                return Number(x) * Number(y);
            }
        })
    );

    server.route({
        method: 'get',
        path: '/add/{a}/{b}',
        handler: (request) => {

            const { a, b } = request.params;
            const { mathService } = request.services();

            return mathService.add(a, b);
        }
    });

    await server.start();

    console.log(`Start adding at ${server.info.uri}`);
})();

Using existing libraries as services

It's also possible to use existing libraries as services in your application. Here's an example of how we might utilize Nodemailer as a service for sending emails. This example features Schmervice.withName(), which is a convenient way to name your service using the Schmervice.name symbol, similarly to the example above:

const Schmervice = require('@hapipal/schmervice');
const Nodemailer = require('nodemailer');
const Hapi = require('@hapi/hapi');

(async () => {

    const server = Hapi.server();

    await server.register(Schmervice);

    server.registerService(
        Schmervice.withName('emailService', () => {

            // Sendmail is a simple transport to configure for testing, but if you're
            // not seeing the sent emails then make sure to check your spam folder.

            return Nodemailer.createTransport({
                sendmail: true
            });
        })
    );

    server.route({
        method: 'get',
        path: '/email/{toAddress}/{message*}',
        handler: async (request) => {

            const { toAddress, message } = request.params;
            const { emailService } = request.services();

            await emailService.sendMail({
                from: '[email protected]',
                to: toAddress,
                subject: 'A message for you',
                text: message
            });

            return { success: true };
        }
    });

    await server.start();

    console.log(`Start emailing at ${server.info.uri}`);
})();

Extras

What is a service layer?

"Service layer" is a very imprecise term because it is utilized in all sorts of different ways by various developers and applications. Our goal here is not to be prescriptive about how you use services. But speaking generally, one might write code in a "service" as a way to group related business logic, data transactions (e.g. saving records to a database), or calls to external APIs. Sometimes the service layer denotes a "headless" interface to all the actions you can take in an application, independent of any transport (such as HTTP), and hiding the app's data layer (or model) from its consumers.

In our case services make up a general-purpose "layer" or part of your codebase– concretely, they're just classes that are instanced once per server. You can use them however you see fit!

hapi actually has a feature deeply related to this concept of services: server methods. We love server methods, but also think they work better as a low-level API than being used directly in medium- and large-sized projects. If you're already familiar with hapi server methods, you can think of schmervice as a tool to ergonomically create and use server methods (plus some other bells and whistles).

版本与发布记录

@hapipal/schmervice 共发布 4 个版本,首次发布于 2020/10/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
3.0.0latest2023/02/273 年前
2.1.02022/11/283 年前
2.1.0-types.0types2022/03/134 年前
2.0.02020/10/296 年前

关于 @hapipal/schmervice 的常见问题

@hapipal/schmervice 是什么?

A service layer for hapi

如何安装 @hapipal/schmervice?

在项目目录运行 npm install @hapipal/schmervice,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@hapi/hapi(>=20 <22)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@hapipal/schmervice 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@hapipal/schmervice 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@hapipal/schmervice 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@hapipal/schmervice 可以商用吗?

@hapipal/schmervice 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@hapipal/schmervice 的下载量有多少?

根据 npm 官方下载统计,@hapipal/schmervice 在 2026/10/17 – 2026/11/15 这 30 天内被下载 8,540 次,日均约 285 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hapipal/schmervice 还在维护吗?

最新版本 3.0.0 发布于 2023/02/27(3 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/10/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。