Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract backend-http-client from node-core #145

Merged
merged 4 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/release.backend-http-client.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Package release to NPM -> backend-http-client
on:
pull_request:
types:
- closed
branches:
- main
paths:
- 'packages/app/backend-http-client/**'

jobs:
call-build-flow:
uses: lokalise/shared-ts-libs/.github/workflows/release.package.yml@main
with:
working_directory: 'packages/app/backend-http-client'
package_name: 'backend-http-client'
secrets:
npm_token: ${{ secrets.NPM_TOKEN }}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "shared-ts-libs",
"version": "1.0.0",
"description": "Opinionated HTTP client for the Node.js backend",
"workspaces": [
"packages/dev/*",
"packages/app/*"
Expand Down
5 changes: 5 additions & 0 deletions packages/app/backend-http-client/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
coverage/
dist/
vitest.config.mts
src/logging/example.script.js
76 changes: 76 additions & 0 deletions packages/app/backend-http-client/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module",
"project": "./tsconfig.lint.json"
},
"ignorePatterns": ["node_modules"],
"plugins": ["@typescript-eslint", "vitest", "import"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:vitest/recommended"
],
"rules": {
"@typescript-eslint/no-empty-interface": "warn",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/indent": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/consistent-type-imports": "warn",
"@typescript-eslint/member-delimiter-style": [
"error",
{
"multiline": {
"delimiter": "none",
"requireLast": false
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"import/order": [
"warn",
{
"alphabetize": { "order": "asc" },
"newlines-between": "always"
}
]
},
"overrides": [
{
"files": ["test/**/*", "*.spec.ts", "*.test.ts"],
"rules": {
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/indent": "off",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/consistent-type-imports": "warn",
"@typescript-eslint/no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
]
}
}
]
}
107 changes: 107 additions & 0 deletions packages/app/backend-http-client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package-lock.json
.idea/

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
12 changes: 12 additions & 0 deletions packages/app/backend-http-client/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.idea/
.npmignore
node_modules/
README.md
test/
.nyc_output/
coverage/
lib/
jest.config.json
package-lock.json
tsconfig.json
.eslintrc.json
13 changes: 13 additions & 0 deletions packages/app/backend-http-client/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2024 Lokalise, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
76 changes: 76 additions & 0 deletions packages/app/backend-http-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# backend-http-client 🧬

Opinionated HTTP client for the Node.js backend

## Overview

The library provides methods to implement the client side of HTTP protocols. Public methods available are:

- `buildClient()`, which returns a [Client](https://undici.nodejs.org/#/docs/api/Client) instance and should be called before any of the following methods with parameters:
- `baseUrl`;
- `clientOptions` – set of [ClientOptions](https://undici.nodejs.org/#/docs/api/Client?id=parameter-clientoptions) (optional). If none are provided, the following default options will be used to instantiate the client:
```
keepAliveMaxTimeout: 300_000,
keepAliveTimeout: 4000,
```
- `sendGet()`;
- `sendPost()`;
- `sendPut()`;
- `sendPutBinary()`;
- `sendDelete()`;
- `sendPatch()`.

All _send_ methods accept a type parameter and the following arguments:

- `client`, the return value of `buildClient()`;
- `path`;
- `options` – (optional). Possible values are:

- `headers`;
- `query`, query string params to be embedded in the request URL;
- `timeout`, the timeout after which a request will time out, in milliseconds. Default is 30 seconds. Pass `undefined` if you prefer to have no timeout;
- `throwOnError`;`
- `reqContext`;
- `safeParseJson`, used when the response content-type is `application/json`. If `true`, the response body will be parsed as JSON and a `ResponseError` will be thrown in case of syntax errors. If `false`, errors are not handled;
- `blobResponseBody`, used when the response body should be returned as Blob;
- `requestLabel`, this string will be returned together with any thrown or returned Error to provide additional context about what request was being executed when the error has happened;
- `disableKeepAlive`;`
- `retryConfig`, defined by:
- `maxAttempts`, the maximum number of times a request should be retried;
- `delayBetweenAttemptsInMsecs`;
- `statusCodesToRetry`, the status codes that trigger a retry;
- `retryOnTimeout`;
- `clientOptions`;
- `responseSchema`, used both for inferring the response type of the call, and also (if `validateResponse` is `true`) for validating the response structure;
- `validateResponse`;

The following options are applied by default:

```
validateResponse: true,
throwOnError: true,
timeout: 30000,
retryConfig: {
maxAttemps: 1,
delayBetweenAttemptsInMsecs: 0,
statusCodesToRetry: [],
retryOnTimeout: false,
}
```

Additionally, `sendPost()`, `sendPut()`, `sendPutBinary()`, and `sendPatch()` also accept a `body` parameter.

The response of any _send_ method will be resolved to always have `result` set, but only have `error` set in case something went wrong. See [Either](#either) for more information.

## Either

The library provides the type `Either` for error handling in the functional paradigm. The two possible values are:

- `result` is defined, `error` is undefined;
- `error` is defined, `result` is undefined.

It's up to the caller of the function to handle the received error or throw an error.

Read [this article](https://antman-does-software.com/stop-catching-errors-in-typescript-use-the-either-type-to-make-your-code-predictable) for more information on how `Either` works and its benefits.

Additionally, `DefiniteEither` is also provided. It is a variation of the aforementioned `Either`, which may or may not have `error` set, but always has `result`.
16 changes: 16 additions & 0 deletions packages/app/backend-http-client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export {
sendPut,
sendPutBinary,
sendDelete,
sendPatch,
sendGet,
sendPost,
sendPostBinary,
httpClient,
buildClient,
type RequestOptions,
type Response,
type HttpRequestContext,
type ResponseSchema,
JSON_HEADERS,
} from './src/httpClient'
58 changes: 58 additions & 0 deletions packages/app/backend-http-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"name": "@lokalise/backend-http-client",
"version": "1.0.0",
"author": {
"name": "Lokalise",
"url": "https://lokalise.com/"
},
"homepage": "https://github.com/lokalise/backend-http-client",
"repository": {
"type": "git",
"url": "git://github.com/lokalise/backend-http-client.git"
},
"license": "Apache-2.0",
"files": [
"dist/**",
"LICENSE.md",
"README.md"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "commonjs",
"private": false,
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "tsc",
"test": "vitest",
"test:coverage": "vitest --coverage",
"test:ci": "npm run lint && npm run test:coverage",
"test:update-snapshots": "vitest -u",
"lint": "eslint . --ext .ts && prettier --check --log-level warn \"**/*.{json,md,ts}\" !CHANGELOG.md",
"lint:fix": "eslint . --fix && prettier --write --log-level warn \"**/*.{json,md,ts}\" !CHANGELOG.md",
"version": "auto-changelog -p && git add CHANGELOG.md",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@lokalise/node-core": "^9.17.1",
"undici": "^6.16.1",
"undici-retry": "^5.0.3",
"zod": "^3.23.8"
},
"devDependencies": {
"@lokalise/prettier-config": "latest",
"@types/node": "^20.12.11",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@vitest/coverage-v8": "1.6.0",
"auto-changelog": "^2.4.0",
"eslint": "^8.57.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-vitest": "0.4.1",
"prettier": "^3.2.5",
"typescript": "^5.4.5",
"vitest": "1.6.0"
},
"prettier": "@lokalise/prettier-config"
}
Loading
Loading