@acter/gateway 中文文档教程

发布于 5年前 浏览 17 项目主页 更新于 3年前

Reaction Gateway

带有大量内置工具的企业平台的简单“让我开发”API 网关 立即将您的想法付诸实践!

尽管 Reaction Gateway 处于预发布阶段,但它已经在生产中使用,每天在全球托管数百万个连接。

TL/DR;

阅读安装入门部分。 此网关已预先配置为开箱即用,但请阅读配置部分以在几秒钟内设置您想要实现的目标,然后您将需要查看服务部分并构建您的第一项服务,也许可以尝试一些预构建的服务,例如 status

Executive summary

Reaction gateway 是一个强大的 API 网关框架的新开源版本,由 20 年经验丰富的软件架构师和专业的 Node 开发人员构建。 这个网关或其衍生产品为许多大公司(包括康卡斯特、ESPN、迪士尼以及许多医院、律师事务所和初创公司)使用的后端提供支持。

将其发布到社区是因为与我合作的许多公司都想将他们拥有的其他平台转移到网关中,但不知道从哪里开始,而且大多数现有网关的学习曲线都很高。

Reaction Gateway 旨在为您提供构建即时后端所需的工具,以便您可以立即开始开发杀手级应用程序。 然而,它具有足够的活力和远见,还可以为您提供一条清晰的路径,使您的后端达到行星规模甚至更远(您可以坚持使用这个网关,并使用像 Kubernetes)。

如果您当前未使用 API 网关,则需要使用 API 网关。

What's a gateway?

API 网关(就是这样),将开发人员意识到他们需要在现代后端中完成的许多事情集中到一个简洁易用的地方。 他们还在您的平台中提供了一个API,允许您的应用程序使用单一平台组件与任何其他应用程序对话。

由于网关包含模块化可插入组件,因此可以将更多平台组件改编为平台方面。 面向方面编程 (AOP) 及其表亲 mixin 已经在开发者社区中大行其道,留下了更好的设计它所到之处的尾迹。 因此,API 网关将这种思维方式带到平台层或最顶层,它当然属于那里。

API 网关是未来。 如果您不相信我,请相信 Google,它最近以 6.25 亿美元

一个设计得当的 API 网关可以为您提供整个平台减去您的服务,包括平台的所有额外“方面”,这些通常是经过深思熟虑才附加的,使您的平台更加健壮、安全和稳定。

毕竟,平台是为了支持您的应用程序或想法,而不是扼杀它。 如果您曾经开发过没有 API 网关的平台,您就会注意到您是多么专注于您的平台而不是平台的意图。 这不好。 让网关向您展示您的烦恼如何像一块美味的巧克力一样融化。

Gateway benefits

网关使得创建上帝对象或整体变得非常困难,并且非常容易开发微服务或现代 FaaS/Lambda 服务。 网关成为您进入世界的中心和唯一接口,并通过平台服务传播工作,业界一致认为这是目前已知的最佳设计。

Query agregation

网关还可以承载现代聚合逻辑,如 GraphQL,消除应用程序为加载单个页面而发出 20 次或更多 API 请求所导致的减速( GraphQL 可以将这 20 个请求转换为一个请求,并且使用水化模式,你可以将其变为零请求)。

Platform features in one place

通过在单个逻辑位置处理缓存、审计、日志记录、安全、黑名单、转换、A/B 测试、ETL 等,网关还大大降低了后端的复杂性。 有没有想过 AWS、GCP 和 Azure 如何持续生产高级和复杂的 SaaS 产品(如 2FA、AI 和 ML)并每月迭代? 它们都使用 API 网关来分离问题 :)

Protocols

网关是您平台的唯一接口,还允许用户使用现代和更快的协议进行连接,例如 WebSocket 如果没有大的学习曲线,开发人员就会接触到(有时称为“回调地狱”)。 例如,WebSocket 是一种应用程序 协议,旨在取代 HTTP。 HTTP 实际上是一种文档协议,旨在托管文档,而不是应用程序)。

Clean separation of concerns

更重要的是,设计得当的网关可以将您的 SPA 清晰且合乎逻辑地划分为前端和后端,允许您交付设计正确、速度如闪电般的 SPA,使用更快的 CDN 提供静态消耗品。

将 CDN 用于前端负载意味着您​​只需关注后端的复杂性(前端的复杂性仅限于开发),而使用网关,您可以进一步降低除简单服务以外的所有内容的复杂性。

Reliability and security

此网关已用于许多产品:

  • Support hundreds of thousands of connections at once using a single instance.
  • Used behind a load balancer in a cluster of over 50 containers to house infinite connections on both GSP and AWS.
  • It has been used to host tens of billions of records.
  • It provides access to the half-terabyte legal database that powers openjurist.org, supplying millions of requests and approximately 1/3rd of all Wikipedia legal references.
  • It is used by medical platforms to provide services for millions of patients.

Installation

<代码> npm i @acter/网关

Getting Started

<代码> const gateway = require('@acter/gateway')

这将为健康检查创建网关和设置端点(完全与 Kubernetes 或其他协调器兼容)。

它还将设置常见的应用默认设置和授权平台(使用 passport,因此您将能够使用 user/pass 对用户进行授权, JWT、Facebook、谷歌,你能想到的,你知道了)。 user/pass 和 JWT 是默认安装的,因为几乎每个人都使用它们。

Passport 支持超过 500 种授权机制。

Configuration

在项目的根目录中创建一个 /config 文件夹,其中包含一个名为 default.xml 的文件。 js

该网关完全支持 node-config 中引入的所有丰富标准。

A word on folders

默认情况下,为了加快开发速度,网关希望您将配置放在 /config 文件夹中,将源代码放在 /src 文件夹中。 创建服务就像将文件放入 src/services 并使用配置启用它一样简单。

Default settings

这些是默认设置和值。 如果您要使用它们,则无需进行任何配置。

module.exports = {
  server: {
    // By default, will try port 8000 and use the next available, override here.
    port: 8000,
    // By default, will use your package.json version, but you can override here.
    version: '0.6.9',
    // Default will output fancy "Acter". Override here.
    logo: require('pathToYourLogoString'),
    // The datasource
    persistence: 'datasource://user:pas@host:port/db',
    // If we're hosting static files or not.
    statics: {
      host: false,
      endpoint: '/remote'.
      folder: 'statics' // The root of your source file + /statics
    }
  },
  services: {
    defaults: {
      model: {
        freezeTableName: true
      },
      pagination: {
        default: 20,
        max: 1000
      }
    },
    definitions: {
      yourServiecName: {
        model: 'yourModelName',
        auto: true // If true, your service will be auto-generated based on your mode.
        config: {
          // Configuration you pass to your service.
        }
      }
    }
  }
}

Connecting your data

Acter 为您提供了许多可以交互的数据源。 安装涉及一个简单的标准连接字符串:

datasource://user:pas@host:port/db

Where:

  • datasource is one of the following: 'mysql', 'mariadb', 'postgres', 'sqlite', 'sqlserver'.
  • user is the username authorized for the datasource.
  • pass is the password authorized for the datasource.
  • host is an IPv4, IPv6 or FDQN (like google.com) that your datasource is located at.
  • port is optional, and only needed if using a nonstandard port for your datasource type.
  • db is the name of the database at the host you provided.

就是这样! 您现在可以完全访问 API 网关中的任何数据源。 这意味着您可以不再担心您使用的是哪个数据源,而是专注于您的应用程序。 例如,您可以使用一个简单的 sqlite 数据源启动一个应用程序,然后当您扩展、升级到 MySQL 时,您可以进一步扩展到 Postgres(Digital Ocean 托管托管等)或 MariaDB(Amazon Aurora、GCP 等) .

当您对数据源进行更改时,完全取决于您,您的源代码只会更改一行配置! :)

有关如何创建服务和访问它们以及向世界公开您的数据的详细信息,请查看服务部分。

Other config options

server.statics

网关可以自动托管静态文件(比如 Apache/nginx,虽然稍微简单一点):)。 为此,Express 处于幕后。 网关支持文件的 gzip 压缩、HTTP 或 HTTPS。 无需部署 NGINX 或 Apache 实例,或移动到 CDN,即可开始使用所需的一切。

默认

{ active: false, folder: 'statics, endpoint: '/remote }

active: 如果你想托管静态资源则为真(比如index.html)。

文件夹:您要托管的文件夹的相对路径。

端点:您要从中提供静态文件的端点。 '/' 代表 root,但将使用与您的服务相同的命名空间,并且可能会重叠或产生意外结果。


server.watch

网关可以自动监视文件夹的变化并将结果发送到您指定的脚本。 实现高级功能,例如在上传文件时更新 UI 等。

默认

{ active: false, folder: undefined, report: undefined }

active:如果您想观看文件夹,则为真。

文件夹:您要观看的文件夹的完整路径。

report:将接收有关您监视的文件夹的报告的脚本。

Report script.

您的报告脚本路径可以是相对的。 它将作为一个函数被调用并传递一个包含以下内容的对象:

{
  app,     // The app object, which lets you attach hooks or call any service
  watcher, // The watcher bus. More on this below
  config,  // The complete config for the gateway
  util     // The gateway util (helper functions) object
}

观察者总线是一个事件总线,它将触发以下事件:

  • ready: You get this event when all the structure in the watched folder have been reported.
  • add: Triggered when a file is added to a watched folder.
  • unlink: Triggered when a file is removed from a watched folder.
  • addDir: Triggered when a folder is added to a watched folder.
  • unlinkDir: Triggered when a folder is removed from a watched folder.
  • error: Triggered when something goes wrong.

所有事件都将传递更改的路径/文件,除了传递的ready什么都没有,error 传递错误对象。

Windows 用户注意:由于底层实现中的一个怪癖,Windows 操作系统在观看“unlinkedDir”时会报告错误。 NodeJS 没有考虑到这一点,也没有考虑到这一点(截至 2019 年 3 月 1 日)。 因此,Acter 无法自动干净地解决此问题

如果你想在 Windows 机器上观看 unlinkedDir,添加一个错误触发器并像这样处理它......

        watcher.on('error', error => {
            // Ignore EPERM errors in windows, which happen if you delete folders...
            if (error.code === 'EPERM' && require('os').platform() === 'win32') return 
            // Otherwise, display the error...
            console.log(error)
        })

这个问题在 Mac 或 Linux 操作系统上不存在。

示例观察报告脚本......

module.exports = ({app, watcher, config, util}) => {
  watcher.on('ready', () => {
      // Can watch these events too: add, unlink, addDir, unlinkDir, error
      watcher.on('add', async path => {
        // As an example, get the total server memory percent used, and which file changed...
        const stat = await app.services.status.find()
        console.log(`(Mem used: ${stat.system.memory.percentUsed}). A new file has been uploaded: "${path}"`)
      })
  })    
}

console.log('Watcher script setup completed.')

server.port

默认

{ from: 8000, to: 8999 }

如果您指定一个数字,除非该端口空闲,否则服务器不会启动。 如果您使用带有“from”和“to”变量的对象指定范围(即 { from: startingPort, to: endingPort }),服务器将找到 该范围内的第一个自由港。 选择的端口将是 使用 config.server.port

server.mode

Default

http

可用于您的应用程序如果您指定“https”,服务器也将需要一个 keycert 指向有效相应文件的值。 这就是激活 HTTPS 所需的全部。 如果启用 HTTPS,WebSocket 也会自动运行在 WSS 中, 使您的整个连接安全。 出于安全原因,您不能同时收听 HTTP 和 HTTPS。 如果你想这样做, 启动第二个网关。 我们认为隔离 HTTP/HTTPS 流量非常重要,我们认为您不应混合在两者中运行的代码。

Technical details

Entry point

acter 逻辑从 src/index.js 开始 绘制徽标,加载配置,启动平台。 Acter 在后台使用调试并以“acter”开头。

Logging

当您的服务执行 console.log() 语句时,它会在前面加上日期/时间戳并将其发送到标准输出。 使用任何服务管理策略将其记录的内容输出到文件或数据源。

Reaction Gateway

Simple "just let me develop" API gateway for your enterprise platform with loads of built-in tools to take your idea to production in no time!

Although reaction gateway is in pre-release, it is already used in production and hosting millions of connections per day around the world.

TL/DR;

Read the installation and getting started sections. This gateway comes pre-configured to just work out of the box, but read the configuration section to setup things you want to achieve in seconds, then you'll want to check out the services section and build your first service, and maybe try out some pre-built services like status.

Executive summary

Reaction gateway is a new Open Source version of a powerful API gateway framework built by a 20 year veteran software architect and an expert Node developer. This gateway, or derivitives of it, power backends used at many large companies including Comcast, ESPN, Disney, and many hospitals, legal firms and startups.

This is being released into the community because many companies I work with want to move other platforms they have into gateways but do not know where to begin, and most existing gateways have a high learning curve.

Reaction gateway is designed to provide you will the tools you need to build an instant backend so you can start developing a killer app immediately. However, it comes with enough juice and foresight to also provide you with a clear path to take your backend to planet scale and beyond (you could stick with this gateway and power a billion connections per second using an orchistrator like Kubernetes).

If you aren't currently using an API Gateway, you NEED to be using an API Gateway.

What's a gateway?

An API Gateway (which this is), centralizes many things developers realized they needed to do in a modern backend into one neat and easy place. They also provide an API into your platform, allowing your app to speak with any other app using a single platform component.

Because gateways house modular pluggable components, further platform components can be adapted as platform aspects. Aspect Oriented Programming (AOP), and it's cousin, the mixin has torn through the developer community, leaving a much better design in the wake of everywhere it travels. Therefore, API gateways bring this style of thinking to the platform layer, or top-most layer, where it certianly belongs.

API Gateways are the future. If you don't believe me believe Google, who recently purchased Apigee (one of the first proponents of API Gateways) for $625 million dollars.

A properly designed API Gateway can provide you with your entire platform minus your services, including all additional "aspects" of a platform that are usually bolted-on as after thoughts, making your platform much more robust, secure and stable.

After all, a platform is meant to support your application or idea, not choke it. If you've ever developed a platform WITHOUT an API gateway, you noticed just how much you focus on your platform instead of your platform's intentions. This is bad. Let a gateway show you how your worries can melt away like a nice piece of chocolate.

Gateway benefits

A gateway makes it very difficult to create God objects or monoliths, and very easy to develop microservices or modern FaaS/Lambda services. The gateway becomes your central and only interface into the world, and spreads work out through platform services, which the industry unanimously agrees is the best current design known.

Query agregation

A gateway can also host modern aggregation logic like GraphQL, eliminating the slowdown caused by 20 or more API requests by your app just to load a single page (GraphQL can convert those 20 requests into a single request, and using the hydration pattern, you can make it zero requests).

Platform features in one place

Gateways also greatly reduce the complexity of your backend by handling caching, auditing, logging, security, blacklisting, conversion, A/B testing, ETL and more in a single logical place. Ever wonder how AWS, GCP and Azure keep producing advanced and complex SaaS products like 2FA, AI and ML and iterate every month? They all use an API Gateway to separate concerns :)

Protocols

Gateways, being the only interface to your platform, also allow users to connect using modern and faster protocols like WebSocket without the large learning curve developers otherwise would get exposed to (sometimes referred to as "callback hell"). WebSocket, for example is an application protocol and was designed to replace HTTP. HTTP is actually a document protocol designed to host documents, not applications).

Clean separation of concerns

What is more, a properly designed gateway can cleanly and logically divide your SPA into a front-end and back-end, allowing you to deliver a correctly designed, lightning speed SPA that can be hosted at 1% of the cost using a much faster CDN to provide static consumables.

Using a CDN for your front-end payload means you only have to focus on the complexity of a backend (frontend complexity is limited to development), and using a gateway, you can further reduce complexity to everything but simple services.

Reliability and security

This gateway has been used on many products that:

  • Support hundreds of thousands of connections at once using a single instance.
  • Used behind a load balancer in a cluster of over 50 containers to house infinite connections on both GSP and AWS.
  • It has been used to host tens of billions of records.
  • It provides access to the half-terabyte legal database that powers openjurist.org, supplying millions of requests and approximately 1/3rd of all Wikipedia legal references.
  • It is used by medical platforms to provide services for millions of patients.

Installation

npm i @acter/gateway

Getting Started

const gateway = require('@acter/gateway')

This will create a gateway and setup endpoints for healthchecking (fully Kubernetes or other orchistrator compatible).

It will also setup common app defaults and an authorization platform (uses passport, so you'll be able to auth users using user/pass, JWT, Facebook, Google, you name it, you got it). user/pass and JWT are installed by default since just about everyone uses them.

Passport supports over 500 authorization mechanisms.

Configuration

Create a /config folder in the root of your project containing a file named default.js.

The gateway fully supports all of the rich standards introduced in node-config.

A word on folders

By default, and to speed up development, the gateway expects you to put your configuration in your /config folder, and your source code in your /src folder. Creating a service is as simple as dropping a file into src/services and enabling it using config.

Default settings

These are default settings and values. If you are going to use them, you have nothing to configure.

module.exports = {
  server: {
    // By default, will try port 8000 and use the next available, override here.
    port: 8000,
    // By default, will use your package.json version, but you can override here.
    version: '0.6.9',
    // Default will output fancy "Acter". Override here.
    logo: require('pathToYourLogoString'),
    // The datasource
    persistence: 'datasource://user:pas@host:port/db',
    // If we're hosting static files or not.
    statics: {
      host: false,
      endpoint: '/remote'.
      folder: 'statics' // The root of your source file + /statics
    }
  },
  services: {
    defaults: {
      model: {
        freezeTableName: true
      },
      pagination: {
        default: 20,
        max: 1000
      }
    },
    definitions: {
      yourServiecName: {
        model: 'yourModelName',
        auto: true // If true, your service will be auto-generated based on your mode.
        config: {
          // Configuration you pass to your service.
        }
      }
    }
  }
}

Connecting your data

Acter provides you with many datasources that you can interact with. Setup involves a simple, standard connection string:

datasource://user:pas@host:port/db

Where:

  • datasource is one of the following: 'mysql', 'mariadb', 'postgres', 'sqlite', 'sqlserver'.
  • user is the username authorized for the datasource.
  • pass is the password authorized for the datasource.
  • host is an IPv4, IPv6 or FDQN (like google.com) that your datasource is located at.
  • port is optional, and only needed if using a nonstandard port for your datasource type.
  • db is the name of the database at the host you provided.

That's it! You now have full access to any datasource within your API gateway. This means you can stop worrying about WHICH datasource you use, and focus on your application. For example you could start an app with a simple sqlite datasource, and then when you expand, upgrade to MySQL, still further, you could expand to Postgres (Digital Ocean managed hosting, etc.) or MariaDB (Amazon Aurora, GCP, etc).

When you make the change on your datasource is totally up to you, and your source code will simply change a single line of configuration! :)

For details on how to create services and access them, exposing your data to the world, please take a look at the services section.

Other config options

server.statics

The gateway can automatically host static files (like Apache/nginx, although a tiny bit simpler) :). Express is under the hood for this. The Gateway supports gzip compression, HTTP or HTTPS for your files. Everything you need to get you started without having to deploy an NGINX or Apache instance, or moving to a CDN.

Default

{ active: false, folder: 'statics, endpoint: '/remote }

active: True if you want to host static resources (like index.html).

folder: The relative path to the folder you want to host.

endpoint: The endpoint you want to serve the static files out of. '/' for root, but will use the same namespace as your services and may overlap or produce unintended results.


server.watch

The gateway can automatically watch folders for changes and send results to a script you specify. Implement advanced things like updating a UI when a file is uploaded, etc.

Default

{ active: false, folder: undefined, report: undefined }

active: True if you want to watch a folder.

folder: The full path to the folder you want to watch.

report: The script that will recieve reports on your watched folder.

Report script.

Your report script path can be relative. It will be called as a function and passed an object containing:

{
  app,     // The app object, which lets you attach hooks or call any service
  watcher, // The watcher bus. More on this below
  config,  // The complete config for the gateway
  util     // The gateway util (helper functions) object
}

The watcher bus is an event bus that will trigger the following events:

  • ready: You get this event when all the structure in the watched folder have been reported.
  • add: Triggered when a file is added to a watched folder.
  • unlink: Triggered when a file is removed from a watched folder.
  • addDir: Triggered when a folder is added to a watched folder.
  • unlinkDir: Triggered when a folder is removed from a watched folder.
  • error: Triggered when something goes wrong.

All events will be passed the path/file that changed except for ready which passes nothing, and error which passes an error object.

NOTE for Windows users: The Windows OS will report an error when watching "unlinkedDir" because of a quirk in the underlying implementation. NodeJS does not account for this or allow for a way to account for this (as of 3/1/2019). Because of this, this issue cannot be cleanly addressed automatically by Acter.

If you want to watch unlinkedDir on a Windows machine, add a trigger for error and handle it like so…

        watcher.on('error', error => {
            // Ignore EPERM errors in windows, which happen if you delete folders...
            if (error.code === 'EPERM' && require('os').platform() === 'win32') return 
            // Otherwise, display the error...
            console.log(error)
        })

This issue does not exist on Mac or Linux OSes.

Example watch report script…

module.exports = ({app, watcher, config, util}) => {
  watcher.on('ready', () => {
      // Can watch these events too: add, unlink, addDir, unlinkDir, error
      watcher.on('add', async path => {
        // As an example, get the total server memory percent used, and which file changed...
        const stat = await app.services.status.find()
        console.log(`(Mem used: ${stat.system.memory.percentUsed}). A new file has been uploaded: "${path}"`)
      })
  })    
}

console.log('Watcher script setup completed.')

server.port

Default

{ from: 8000, to: 8999 }

If you specify a number, the server will not start unless that port is free. If you specify a range using an object with "from" and "to" variables (i.e. { from: startingPort, to: endingPort }), the server will find the first free port within that range. The port that was chosen will be available to your application using config.server.port

server.mode

Default

http

If you specify 'https', the server will also expect a key and cert value that point to valid respective files. That's all you need to activate HTTPS. If you enable HTTPS, WebSocket will also operate in WSS automatically, making your entire connection secure. You cannot listen to HTTP and HTTPS at the same time for security reasons. If you want to do this, fire up a second gateway. We feel it's so important to isolate HTTP/HTTPS traffic that we don't believe you should mix code running in both.

Technical details

Entry point

Acter logic starts at src/index.js The logo is drawn, configuration is loaded, and the platform is started. Acter uses debug under the hood and starts with 'acter'.

Logging

When your service executes console.log() statements it will prepend a date/timestamp and send it to standard out. Use any service management strategy to output what it logs to files or datasources.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文