npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

heirloom-api-plugin

v1.0.6

Published

[![NPM Downloads](https://img.shields.io/npm/dm/heirloom-api-plugin.svg?style=flat)](https://npmjs.org/package/heirloom-api-plugin) [![Node.js Version](https://img.shields.io/node/v/heirloom-api-plugin.svg?style=flat)](http://nodejs.org/download/) [![Buil

Downloads

7

Readme

heirloom-api-plugin NPM version

NPM Downloads Node.js Version Build Status

基于heirloom-corePlugin接口,对koa-router^7.1.1的封装实现。

遵循规约重于配置的思想,扫描指定文件目录下的JS文件,按照文件目录层级自动映射成为路由。

e.g:

  • project/api/v1/sample.js -> http://domain.com/api/v1/sample;
  • project/api/v1/sample/index.js -> http://domain.com/api/v1/sample;
  • project/api/index.js -> http://domain.com/api;

相关项目

快速开始

执行以下命令新建工程目录:example/

mkdir example && cd example && npm init

进入example/目录,执行以下命令安装依赖:

npm install heirloom-core heirloom-api-plugin --save

编写example/index.js:

const NormalServer = require('heirloom-core').NormalServer;
const KoaEngine = require('heirloom-core').KoaEngine;
const HeirloomAPIPlugin = require('heirloom-api-plugin').HeirloomAPIPlugin;

const server = new NormalServer({
    logger: console,
    port: 4000,
    engine: KoaEngine.shareInstance(),
});

server.apply(new HeirloomAPIPlugin());

server.start();

编写example/api/sample.js文件,实现用于生产环境的API:

// GET请求
exports.get = function (ctx) {
    ctx.body = 'production';
};

编写example/api/__mocks__/sample.js文件,Mock接口:

// GET请求
exports.get = function (ctx) {
    ctx.body = 'staging';
};

example/目录,执行以下命令启动服务:

node .

另起一个终端访问:

curl http://localhost:4000/api/sample # 返回:staging

结束之前启动的进程,加上环境变量NODE_ENV再次启动服务:

NODE_ENV=production node .

另起一个终端访问:

curl http://localhost:4000/api/sample # 返回:production

类型定义

// HTTP Methods
declare type Heirloom$AllowedMethod = $Enum<{ get: string, post: string, update: string, patch: string, delete: string, put: string }>;

// Controller, 单个或多个Function,多个Function时详见:https://github.com/alexmingoia/koa-router#multiple-middleware
declare type Heirloom$Controller = Function | Array<Function>;

// API.js
declare type Heirloom$API = { [key: Heirloom$AllowedMethod]: Heirloom$Controller };

// HeirloomAPIPlugin类构造参数
declare type Heirloom$APIPluginOptions = {
    mock: boolean, // 是否启用mock,缺省(默认)为:process.env.NODE_ENV !== 'production',即在NODE_ENV环境变量值为`production`时关闭mock。
    scanDirectory: string, // 扫描目录,缺省(默认)为:api/
    apiRoot: string, // 路由前缀,缺省(默认)为:/api,即:http://domain.com/api/path/to/something,如有需要可指定为:/,即:http://domain.com/path/to/something
};

// HeirloomAPIPlugin类
declare class HeirloomAPIPlugin {
    constructor(options: Heirloom$APIPluginOptions): HeirloomAPIPlugin;
}

根据Heirloom$API实现其他类型的请求的接口

example/api/sample.js:

// POST api/sample
exports.post = function (ctx) {
    ctx.body = 'post';
};

// PATCH api/sample
exports.patch = function (ctx) {
    ctx.body = 'patch';
};

// DELETE api/sample
exports.delete = function (ctx) {
    ctx.body = 'post';
};

// update、put...略

路径参数(Path Variables)

example/api/sample.js:

// GET: api/sample/1
function get(ctx) {
    ctx.body = { id: ctx.params.id }; // { id: 1 }
}

get.params = ':id';

exports.get = get;

ES6 Class

require('isomorphic-fetch');

class SampleAPI {

    async get(ctx) {
        const username = ctx.query.username;
        const response = await fetch(`https://api.github.com/users/${username}`);
        if (response.ok) {
            ctx.body = await response.json();
        } else {
            const text = await response.text();
            throw new Error(text);
        }
    }

    async post(ctx) {
    }

}

module.exports = new SampleAPI();

Mock

正式环境 | Mock | 请求 | --------|------|----- /api/v1/sample/index.js|/api/v1/sample/__mocks__/index.js|http://domain.com/api/v1/sample| /api/v1/sample.js | /api/v1/__mocks__/sample.js | http://domain.com/api/v1/sample|