@openapi-typescript-infra/service 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/.eslintignore +7 -0
  2. package/.eslintrc.js +14 -0
  3. package/.github/workflows/codeql-analysis.yml +74 -0
  4. package/.github/workflows/nodejs.yml +23 -0
  5. package/.github/workflows/npmpublish.yml +35 -0
  6. package/.husky/pre-commit +6 -0
  7. package/.prettierrc.js +14 -0
  8. package/@types/config.d.ts +56 -0
  9. package/CHANGELOG.md +5 -0
  10. package/LICENSE +21 -0
  11. package/README.md +28 -0
  12. package/SECURITY.md +12 -0
  13. package/__tests__/config.test.ts +31 -0
  14. package/__tests__/fake-serv/api/fake-serv.yaml +48 -0
  15. package/__tests__/fake-serv/config/config.json +15 -0
  16. package/__tests__/fake-serv/src/handlers/hello.ts +10 -0
  17. package/__tests__/fake-serv/src/index.ts +29 -0
  18. package/__tests__/fake-serv/src/routes/error.ts +13 -0
  19. package/__tests__/fake-serv/src/routes/index.ts +22 -0
  20. package/__tests__/fake-serv/src/routes/other/world.ts +7 -0
  21. package/__tests__/fake-serv.test.ts +74 -0
  22. package/build/bin/start-service.d.ts +2 -0
  23. package/build/bin/start-service.js +31 -0
  24. package/build/bin/start-service.js.map +1 -0
  25. package/build/bootstrap.d.ts +16 -0
  26. package/build/bootstrap.js +90 -0
  27. package/build/bootstrap.js.map +1 -0
  28. package/build/config/index.d.ts +10 -0
  29. package/build/config/index.js +98 -0
  30. package/build/config/index.js.map +1 -0
  31. package/build/config/schema.d.ts +48 -0
  32. package/build/config/schema.js +3 -0
  33. package/build/config/schema.js.map +1 -0
  34. package/build/config/shortstops.d.ts +31 -0
  35. package/build/config/shortstops.js +109 -0
  36. package/build/config/shortstops.js.map +1 -0
  37. package/build/config/types.d.ts +3 -0
  38. package/build/config/types.js +3 -0
  39. package/build/config/types.js.map +1 -0
  40. package/build/development/port-finder.d.ts +1 -0
  41. package/build/development/port-finder.js +41 -0
  42. package/build/development/port-finder.js.map +1 -0
  43. package/build/development/repl.d.ts +2 -0
  44. package/build/development/repl.js +29 -0
  45. package/build/development/repl.js.map +1 -0
  46. package/build/env.d.ts +2 -0
  47. package/build/env.js +19 -0
  48. package/build/env.js.map +1 -0
  49. package/build/error.d.ts +25 -0
  50. package/build/error.js +28 -0
  51. package/build/error.js.map +1 -0
  52. package/build/express-app/app.d.ts +6 -0
  53. package/build/express-app/app.js +327 -0
  54. package/build/express-app/app.js.map +1 -0
  55. package/build/express-app/index.d.ts +2 -0
  56. package/build/express-app/index.js +19 -0
  57. package/build/express-app/index.js.map +1 -0
  58. package/build/express-app/internal-server.d.ts +3 -0
  59. package/build/express-app/internal-server.js +34 -0
  60. package/build/express-app/internal-server.js.map +1 -0
  61. package/build/express-app/route-loader.d.ts +2 -0
  62. package/build/express-app/route-loader.js +46 -0
  63. package/build/express-app/route-loader.js.map +1 -0
  64. package/build/express-app/types.d.ts +14 -0
  65. package/build/express-app/types.js +3 -0
  66. package/build/express-app/types.js.map +1 -0
  67. package/build/index.d.ts +8 -0
  68. package/build/index.js +25 -0
  69. package/build/index.js.map +1 -0
  70. package/build/openapi.d.ts +5 -0
  71. package/build/openapi.js +78 -0
  72. package/build/openapi.js.map +1 -0
  73. package/build/service-calls/index.d.ts +16 -0
  74. package/build/service-calls/index.js +85 -0
  75. package/build/service-calls/index.js.map +1 -0
  76. package/build/telemetry/fetchInstrumentation.d.ts +50 -0
  77. package/build/telemetry/fetchInstrumentation.js +144 -0
  78. package/build/telemetry/fetchInstrumentation.js.map +1 -0
  79. package/build/telemetry/index.d.ts +6 -0
  80. package/build/telemetry/index.js +80 -0
  81. package/build/telemetry/index.js.map +1 -0
  82. package/build/telemetry/instrumentations.d.ts +29 -0
  83. package/build/telemetry/instrumentations.js +47 -0
  84. package/build/telemetry/instrumentations.js.map +1 -0
  85. package/build/telemetry/requestLogger.d.ts +6 -0
  86. package/build/telemetry/requestLogger.js +144 -0
  87. package/build/telemetry/requestLogger.js.map +1 -0
  88. package/build/tsconfig.build.tsbuildinfo +1 -0
  89. package/build/types.d.ts +77 -0
  90. package/build/types.js +3 -0
  91. package/build/types.js.map +1 -0
  92. package/config/config.json +31 -0
  93. package/config/development.json +11 -0
  94. package/config/test.json +5 -0
  95. package/jest.config.js +14 -0
  96. package/package.json +111 -0
  97. package/src/bin/start-service.ts +28 -0
  98. package/src/bootstrap.ts +112 -0
  99. package/src/config/index.ts +115 -0
  100. package/src/config/schema.ts +66 -0
  101. package/src/config/shortstops.ts +118 -0
  102. package/src/config/types.ts +5 -0
  103. package/src/development/port-finder.ts +40 -0
  104. package/src/development/repl.ts +24 -0
  105. package/src/env.ts +14 -0
  106. package/src/error.ts +44 -0
  107. package/src/express-app/app.ts +399 -0
  108. package/src/express-app/index.ts +2 -0
  109. package/src/express-app/internal-server.ts +31 -0
  110. package/src/express-app/route-loader.ts +48 -0
  111. package/src/express-app/types.ts +31 -0
  112. package/src/index.ts +8 -0
  113. package/src/openapi.ts +67 -0
  114. package/src/service-calls/index.ts +129 -0
  115. package/src/telemetry/fetchInstrumentation.ts +209 -0
  116. package/src/telemetry/index.ts +69 -0
  117. package/src/telemetry/instrumentations.ts +54 -0
  118. package/src/telemetry/requestLogger.ts +193 -0
  119. package/src/types.ts +139 -0
  120. package/tsconfig.build.json +10 -0
  121. package/tsconfig.json +36 -0
package/.eslintignore ADDED
@@ -0,0 +1,7 @@
1
+ build/
2
+ coverage
3
+ jest.config.js
4
+ .eslintrc.js
5
+ coconfig.?s
6
+ src/generated
7
+ node_modules
package/.eslintrc.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This file is generated by coconfig. Do not edit it directly.
3
+ * Instead, edit the coconfig.js or coconfig.ts file in your project root.
4
+ *
5
+ * See https://github.com/gas-buddy/coconfig for more information.
6
+ * @version coconfig@0.10.1
7
+ */
8
+ const configModule = require('@openapi-typescript-infra/coconfig');
9
+
10
+ const configItem = configModule.default || configModule.config || configModule;
11
+ const { configuration } = configItem && configItem['.eslintrc.js'];
12
+ const resolved = typeof configuration === 'function' ? configuration() : configuration;
13
+
14
+ module.exports = resolved;
@@ -0,0 +1,74 @@
1
+ # For most projects, this workflow file will not need changing; you simply need
2
+ # to commit it to your repository.
3
+ #
4
+ # You may wish to alter this file to override the set of languages analyzed,
5
+ # or to provide custom queries or build logic.
6
+ #
7
+ # ******** NOTE ********
8
+ # We have attempted to detect the languages in your repository. Please check
9
+ # the `language` matrix defined below to confirm you have the correct set of
10
+ # supported CodeQL languages.
11
+ #
12
+ name: "CodeQL"
13
+
14
+ on:
15
+ push:
16
+ branches: [ "main" ]
17
+ pull_request:
18
+ # The branches below must be a subset of the branches above
19
+ branches: [ "main" ]
20
+ schedule:
21
+ - cron: '38 16 * * 6'
22
+
23
+ jobs:
24
+ analyze:
25
+ name: Analyze
26
+ runs-on: ubuntu-latest
27
+ permissions:
28
+ actions: read
29
+ contents: read
30
+ security-events: write
31
+
32
+ strategy:
33
+ fail-fast: false
34
+ matrix:
35
+ language: [ 'javascript' ]
36
+ # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37
+ # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
38
+
39
+ steps:
40
+ - name: Checkout repository
41
+ uses: actions/checkout@v3
42
+
43
+ # Initializes the CodeQL tools for scanning.
44
+ - name: Initialize CodeQL
45
+ uses: github/codeql-action/init@v2
46
+ with:
47
+ languages: ${{ matrix.language }}
48
+ # If you wish to specify custom queries, you can do so here or in a config file.
49
+ # By default, queries listed here will override any specified in a config file.
50
+ # Prefix the list here with "+" to use these queries and those in the config file.
51
+
52
+ # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
53
+ # queries: security-extended,security-and-quality
54
+
55
+
56
+ # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
57
+ # If this step fails, then you should remove it and run the build manually (see below)
58
+ - name: Autobuild
59
+ uses: github/codeql-action/autobuild@v2
60
+
61
+ # ℹ️ Command-line programs to run using the OS shell.
62
+ # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
63
+
64
+ # If the Autobuild fails above, remove it and uncomment the following three lines.
65
+ # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
66
+
67
+ # - run: |
68
+ # echo "Run, Build Application using script"
69
+ # ./location_of_script_within_repo/buildscript.sh
70
+
71
+ - name: Perform CodeQL Analysis
72
+ uses: github/codeql-action/analyze@v2
73
+ with:
74
+ category: "/language:${{matrix.language}}"
@@ -0,0 +1,23 @@
1
+ name: Node CI
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+
8
+ runs-on: ubuntu-latest
9
+
10
+ steps:
11
+ - uses: actions/checkout@v1
12
+ - name: Use Node.js 18
13
+ uses: actions/setup-node@v3
14
+ with:
15
+ node-version: 18
16
+ - name: npm install, lint, build, and test
17
+ run: |
18
+ yarn install --immutable
19
+ yarn lint
20
+ yarn build
21
+ yarn test
22
+ env:
23
+ CI: true
@@ -0,0 +1,35 @@
1
+ name: Node.js Package
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v1
13
+ - uses: actions/setup-node@v3
14
+ with:
15
+ node-version: 18
16
+ - run: yarn install --immutable
17
+ - run: yarn lint
18
+ - run: yarn test
19
+ - run: yarn build
20
+
21
+ publish-npm:
22
+ needs: build
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - uses: actions/checkout@v1
26
+ - uses: actions/setup-node@v3
27
+ with:
28
+ node-version: 18
29
+ registry-url: https://registry.npmjs.org/
30
+ - run: yarn install --immutable
31
+ - run: yarn build
32
+ - run: npm publish --access public
33
+ env:
34
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
35
+
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
+
4
+ yarn lint-staged
5
+ yarn build
6
+ yarn test
package/.prettierrc.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This file is generated by coconfig. Do not edit it directly.
3
+ * Instead, edit the coconfig.js or coconfig.ts file in your project root.
4
+ *
5
+ * See https://github.com/gas-buddy/coconfig for more information.
6
+ * @version coconfig@0.10.1
7
+ */
8
+ const configModule = require('@openapi-typescript-infra/coconfig');
9
+
10
+ const configItem = configModule.default || configModule.config || configModule;
11
+ const { configuration } = configItem && configItem['.prettierrc.js'];
12
+ const resolved = typeof configuration === 'function' ? configuration() : configuration;
13
+
14
+ module.exports = resolved;
@@ -0,0 +1,56 @@
1
+ /* eslint-disable import/no-default-export */
2
+ declare module 'shortstop-handlers' {
3
+ export function require(module: string): ReturnType<NodeRequire>;
4
+ export function env(): (envVarName: string) => string | undefined;
5
+ export function base64(): (blob: string) => Buffer;
6
+ export function path(baseDir?: string): (relativePath: string) => string;
7
+ export function file(baseDir?: string): (relativePath: string) => Buffer | string;
8
+ }
9
+
10
+ declare module 'shortstop-yaml' {
11
+ export default function yaml<T>(
12
+ basepath: string,
13
+ ): (path: string, callback: (error?: Error, result?: T) => void) => void;
14
+ }
15
+
16
+ declare module 'shortstop-dns' {
17
+ export default function dns(opts?: {
18
+ family?: number;
19
+ all?: boolean;
20
+ }): (address: string, callback: (error?: Error, result?: string[]) => void) => void;
21
+ }
22
+
23
+ declare module '@gasbuddy/confit' {
24
+ type Json = ReturnType<typeof JSON.parse>
25
+
26
+ export type ProtocolFn<CallbackType> = (value: Json, callback?: (error?: Error, result?: CallbackType) => void) => void;
27
+
28
+ interface ProtocolsSetPrivate<C> {
29
+ [protocol: string]: ProtocolFn<C> | ProtocolFn<C>[];
30
+ }
31
+
32
+ interface ConfigStore {
33
+ get<T>(name: string): T | undefined;
34
+ set<T>(name: string, newValue: T): T;
35
+ use(newSettings: unknown): void;
36
+ }
37
+
38
+ type Options<C> = {
39
+ basedir: string;
40
+ protocols: ProtocolsSetPrivate<C>;
41
+ };
42
+
43
+ interface ConfigFactory {
44
+ create(callback: (err: Error, config: ConfigStore) => unknown): void;
45
+ addOverride(filepathOrSettingsObj: string | object): this;
46
+ addDefault(filepathOrSettingsObj: string | object): this;
47
+ }
48
+
49
+ function confit<C>(optionsOrBaseDir: Options<C> | string): ConfigFactory;
50
+
51
+ namespace confit {
52
+ export type ProtocolsSet<C> = ProtocolsSetPrivate<C>
53
+ }
54
+
55
+ export default confit;
56
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ 1.0.0
2
+ =====
3
+
4
+ * Migrated from @gas-buddy organization to openapi-typescript-infra
5
+ * Reworked some GB specific wording
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2016 GasBuddy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ @gasbuddy/service
2
+ =================
3
+
4
+ [![Node CI](https://github.com/openapi-typescript-infra/openapi-typescript-service/actions/workflows/nodejs.yml/badge.svg)](https://github.com/openapi-typescript-infra/openapi-typescript-service/actions/workflows/nodejs.yml)
5
+
6
+ An opinionated framework for building high scale services - web, api, or job. Uses OpenAPI, pino, express, confit, Typescript and jest.
7
+
8
+ This module creates an environment that makes it simpler to host a REST service
9
+ (less repetition, more enterprise grade features). Wherever possible, we use off
10
+ the shelf infrastructure (OpenAPI, Express@5, Terminus are examples). The goal is to allow
11
+ you to enjoy a high level of type safety with a low tax in type construction in a
12
+ microservice environment.
13
+
14
+ The module takes care of configuration-driven:
15
+
16
+ * body logging
17
+ * json parsing
18
+ * error handling
19
+ * hosted OpenAPI documents/handlers
20
+ * traditional routing
21
+ * graceful shutdown
22
+ * health checks
23
+ * Telemetry and instrumentation
24
+
25
+ services built with this module use Typescript with Node 18, which involves transpilation.
26
+ This module takes that into account across the development and production experience.
27
+
28
+ This needs lots more documentation... Just a start.
package/SECURITY.md ADDED
@@ -0,0 +1,12 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ | ------- | ------------------ |
7
+ | 11.0.x | :white_check_mark: |
8
+ | < 11.0 | :x: |
9
+
10
+ ## Reporting a Vulnerability
11
+
12
+ File an issue win this repo and you can expect a response within 1 business day. @djMax is the primary contact.
@@ -0,0 +1,31 @@
1
+ import path from 'path';
2
+
3
+ import { insertConfigurationBefore, loadConfiguration } from '../src/config';
4
+
5
+ describe('configuration loader', () => {
6
+ test('overrides and shortstops', async () => {
7
+ const rootDirectory = path.resolve(__dirname, './fake-serv');
8
+ const config = await loadConfiguration({
9
+ name: 'fake-serv',
10
+ rootDirectory,
11
+ configurationDirectories: [path.resolve(rootDirectory, './config')],
12
+ });
13
+ expect(config.get('logging:level')).toEqual('debug');
14
+ expect(config.get('google')).toBeTruthy();
15
+ expect(config.get('google')).not.toEqual('google.com');
16
+
17
+ expect(config.get('envswitchoff')).toBeFalsy();
18
+ expect(config.get('envswitchon')).toBeTruthy();
19
+
20
+ expect(config.get('servicetype')).toBeTruthy();
21
+ expect(config.get('notservicetype')).toBeFalsy();
22
+
23
+ const orig = ['a', 'b', 'd'];
24
+ const withC = insertConfigurationBefore(orig, 'c', 'd');
25
+ expect(withC).toEqual(['a', 'b', 'c', 'd']);
26
+ const withE = insertConfigurationBefore(orig, 'e', 'q');
27
+ expect(withE).toEqual(['a', 'b', 'd', 'e', 'q']);
28
+ expect(insertConfigurationBefore(undefined, 'a', 'b')).toEqual(['a', 'b']);
29
+ expect(insertConfigurationBefore([], 'a', 'b')).toEqual(['a', 'b']);
30
+ });
31
+ });
@@ -0,0 +1,48 @@
1
+ openapi: 3.0.0
2
+ info:
3
+ title: Fake Service
4
+ version: 1.0.0
5
+ paths:
6
+ /hello:
7
+ get:
8
+ description: Get a greeting
9
+ parameters:
10
+ - name: greeting
11
+ in: query
12
+ required: false
13
+ schema:
14
+ type: string
15
+ - name: number
16
+ in: query
17
+ required: false
18
+ schema:
19
+ type: number
20
+ - name: break_things
21
+ in: query
22
+ required: false
23
+ schema:
24
+ type: boolean
25
+ responses:
26
+ 200:
27
+ description: We responded
28
+ content:
29
+ application/json:
30
+ schema:
31
+ type: object
32
+ properties:
33
+ greeting:
34
+ type: string
35
+ post:
36
+ description: Test body conversion
37
+ requestBody:
38
+ content:
39
+ application/json:
40
+ schema:
41
+ type: object
42
+ properties:
43
+ number:
44
+ type: number
45
+ required: true
46
+ responses:
47
+ 204:
48
+ description: I heard you
@@ -0,0 +1,15 @@
1
+ {
2
+ "logging": {
3
+ "level": "debug"
4
+ },
5
+ "google": "dns:google.com",
6
+ "envswitchoff": "env_switch:ENV_VAR_DOESNT_EXIST",
7
+ "envswitchon": "env_switch:!ENV_VAR_DOESNT_EXIST",
8
+ "servicetype": "servicetype:serv",
9
+ "notservicetype": "servicetype:api",
10
+ "server": {
11
+ "metrics": {
12
+ "enabled": true
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,10 @@
1
+ import { ServiceHandler } from '../../../../src/index';
2
+ import { FakeServLocals } from '../index';
3
+
4
+ export const get: ServiceHandler<FakeServLocals> = async (req, res) => {
5
+ res.json({ greeting: req.query.greeting || 'Hello World' });
6
+ };
7
+
8
+ export const post: ServiceHandler<FakeServLocals> = async (req, res) => {
9
+ res.sendStatus(204);
10
+ };
@@ -0,0 +1,29 @@
1
+ import { RestApiErrorResponse, RestApiSuccessResponse } from 'rest-api-support';
2
+
3
+ import type { Service, ServiceLocals } from '../../../src/types';
4
+
5
+ export interface FakeServLocals extends ServiceLocals {
6
+ services: {
7
+ fakeServ: {
8
+ get_something(): RestApiSuccessResponse<{ things: string[] }> | RestApiErrorResponse;
9
+ }
10
+ }
11
+ }
12
+
13
+ export function service(): Service<FakeServLocals> {
14
+ return {
15
+ start(app) {
16
+ app.locals.services.fakeServ = {
17
+ get_something() { throw new Error('Should not be called.'); },
18
+ };
19
+ },
20
+ onRequest(req, res) {
21
+ res.locals.rawBody = true;
22
+ },
23
+ async healthy() {
24
+ return new Promise((accept) => {
25
+ setTimeout(accept, 1000);
26
+ });
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,13 @@
1
+ import { ServiceRouter } from '../../../../src/index';
2
+ import { ServiceError } from '../../../../src/error';
3
+
4
+ export function route(router: ServiceRouter) {
5
+ router.get('/sync', (req) => {
6
+ throw new ServiceError(req.app, 'Synchronous error', { code: 'SyncError' });
7
+ });
8
+
9
+ router.get('/async', async (req) => {
10
+ await new Promise((accept) => { setTimeout(accept, 100); })
11
+ .then(() => { throw new ServiceError(req.app, 'Async error', { code: 'AsyncError' }); });
12
+ });
13
+ }
@@ -0,0 +1,22 @@
1
+ import type { ServiceExpress, ServiceRouter } from '../../../../src';
2
+ import { FakeServLocals } from '../index';
3
+
4
+ export function route(
5
+ router: ServiceRouter<FakeServLocals>,
6
+ app: ServiceExpress<FakeServLocals>,
7
+ ) {
8
+ const worldRequests = app.locals.meter.createCounter('world_requests', {
9
+ description: 'Metrics about requests to world',
10
+ });
11
+
12
+ router.get('/world', (req, res) => {
13
+ worldRequests.add(1, { method: 'get' });
14
+ res.json({ hello: 'world' });
15
+ });
16
+
17
+ router.post('/world', async (req, res) => {
18
+ await app.locals.services.fakeServ.get_something();
19
+ worldRequests.add(1);
20
+ res.sendStatus(204);
21
+ });
22
+ }
@@ -0,0 +1,7 @@
1
+ import type { Router } from 'express';
2
+
3
+ export function route(router: Router) {
4
+ router.get('/', (req, res) => {
5
+ res.json({ hello: 'jupiter' });
6
+ });
7
+ }
@@ -0,0 +1,74 @@
1
+ import path from 'path';
2
+
3
+ import request from 'supertest';
4
+
5
+ import {
6
+ listen, ServiceStartOptions, shutdownApp, startApp,
7
+ } from '../src/index';
8
+
9
+ import { FakeServLocals, service } from './fake-serv/src/index';
10
+
11
+ describe('fake-serv', () => {
12
+ test('basic service functionality', async () => {
13
+ const options: ServiceStartOptions<FakeServLocals> = {
14
+ service,
15
+ name: 'fake-serv',
16
+ rootDirectory: path.resolve(__dirname, './fake-serv'),
17
+ codepath: 'src',
18
+ };
19
+ const app = await startApp(options).catch((error) => {
20
+ console.error(error);
21
+ throw error;
22
+ });
23
+ expect(app).toBeTruthy();
24
+
25
+ let { body } = await request(app).get('/world').timeout(500).expect(200);
26
+ expect(body.hello).toEqual('world');
27
+
28
+ ({ body } = await request(app).get('/other/world').timeout(500).expect(200));
29
+ expect(body.hello).toEqual('jupiter');
30
+
31
+ ({ body } = await request(app).get('/hello').query({ greeting: 'Hello Pluto!', number: '6', break_things: true }).expect(200));
32
+ expect(body.greeting).toEqual('Hello Pluto!');
33
+
34
+ // Can't convert green to a number
35
+ await request(app).get('/hello').query({ greeting: 'Hello Pluto!', number: 'green' }).expect(400);
36
+
37
+ // Make sure body paramater conversion works
38
+ await request(app).post('/hello').send({ number: 'green' }).expect(400);
39
+ await request(app).post('/hello').send({ number: '6' }).expect(204);
40
+ await request(app).post('/hello').send({ number: 6 }).expect(204);
41
+
42
+ ({ body } = await request(app).get('/error/sync').timeout(1000).expect(500));
43
+ expect(body.code).toEqual('SyncError');
44
+
45
+ ({ body } = await request(app).get('/error/async').timeout(1000).expect(500));
46
+ expect(body.code).toEqual('AsyncError');
47
+
48
+ // Mocking
49
+ await request(app).post('/world').expect(500);
50
+
51
+ // Clean shutdown
52
+ await expect(shutdownApp(app)).resolves.toBeUndefined();
53
+ const secondApp = await startApp(options);
54
+
55
+ // Make sure we can listen
56
+ const server = await listen(secondApp);
57
+
58
+ // Call metrics
59
+ await request(secondApp).get('/world').expect(200);
60
+ await request(secondApp.locals.internalApp).get('/metrics')
61
+ .expect(200)
62
+ .expect((res) => expect(res.text).toMatch(/world_requests_total{method="get"} 1/));
63
+
64
+ await new Promise<void>((accept, reject) => {
65
+ server.close((e) => {
66
+ if (e) {
67
+ reject(e);
68
+ } else {
69
+ accept();
70
+ }
71
+ });
72
+ });
73
+ });
74
+ });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const minimist_1 = __importDefault(require("minimist"));
8
+ const repl_1 = require("../development/repl");
9
+ const env_1 = require("../env");
10
+ const bootstrap_1 = require("../bootstrap");
11
+ /**
12
+ * built - forces the use of the build directory. Defaults to true in stage/prod, not in dev
13
+ * repl - launch the REPL (defaults to disabling telemetry)
14
+ * telemetry - whether to use OpenTelemetry. Defaults to false in dev or with repl
15
+ * nobind - do not listen on http port or expose metrics
16
+ */
17
+ const argv = (0, minimist_1.default)(process.argv.slice(2), {
18
+ boolean: ['built', 'repl', 'telemetry', 'nobind'],
19
+ });
20
+ const noTelemetry = (argv.repl || (0, env_1.isDev)()) && !argv.telemetry;
21
+ (0, bootstrap_1.bootstrap)({
22
+ ...argv,
23
+ telemetry: !noTelemetry,
24
+ }).then(({ app, server }) => {
25
+ if (argv.repl) {
26
+ (0, repl_1.serviceRepl)(app, () => {
27
+ server?.close();
28
+ });
29
+ }
30
+ });
31
+ //# sourceMappingURL=start-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-service.js","sourceRoot":"","sources":["../../src/bin/start-service.ts"],"names":[],"mappings":";;;;;;AACA,wDAAgC;AAEhC,8CAAkD;AAClD,gCAA+B;AAC/B,4CAAyC;AAEzC;;;;;GAKG;AACH,MAAM,IAAI,GAAG,IAAA,kBAAQ,EAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IAC3C,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC;CAClD,CAAC,CAAC;AAEH,MAAM,WAAW,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,IAAA,WAAK,GAAE,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC;AAC9D,IAAA,qBAAS,EAAC;IACR,GAAG,IAAI;IACP,SAAS,EAAE,CAAC,WAAW;CACxB,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;IAC1B,IAAI,IAAI,CAAC,IAAI,EAAE;QACb,IAAA,kBAAW,EAAC,GAAG,EAAE,GAAG,EAAE;YACpB,MAAM,EAAE,KAAK,EAAE,CAAC;QAClB,CAAC,CAAC,CAAC;KACJ;AACH,CAAC,CAAC,CAAC"}
@@ -0,0 +1,16 @@
1
+ /// <reference types="node" />
2
+ import type { RequestLocals, ServiceLocals } from './types';
3
+ interface BootstrapArguments {
4
+ name?: string;
5
+ main?: string;
6
+ root?: string;
7
+ built?: boolean;
8
+ packageDir?: string;
9
+ telemetry?: boolean;
10
+ nobind?: boolean;
11
+ }
12
+ export declare function bootstrap<SLocals extends ServiceLocals = ServiceLocals, RLocals extends RequestLocals = RequestLocals>(argv?: BootstrapArguments): Promise<{
13
+ server: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse> | undefined;
14
+ app: import("./types").ServiceExpress<SLocals>;
15
+ }>;
16
+ export {};