Skip to content

Commit

Permalink
refactor: split out a requests library
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfreska committed Apr 15, 2024
1 parent 1777892 commit 68261fb
Show file tree
Hide file tree
Showing 15 changed files with 265 additions and 28 deletions.
5 changes: 5 additions & 0 deletions .changeset/slow-ties-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@siafoundation/request': minor
---

Introduced a new request library for shared request and network code.
3 changes: 2 additions & 1 deletion libs/react-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"swr": "^2.1.1",
"axios": "^0.27.2",
"use-local-storage-state": "^18.3.3",
"@siafoundation/next": "^0.1.3"
"@siafoundation/next": "^0.1.3",
"@siafoundation/request": "0.0.0"
},
"dependencies": {
"detect-gpu": "^5.0.34"
Expand Down
28 changes: 1 addition & 27 deletions libs/react-core/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ import { AxiosRequestConfig, AxiosResponse, AxiosResponseHeaders } from 'axios'
import { MutatorCallback, MutatorOptions } from 'swr'
import { SWROptions } from './types'
import { AppSettings } from './useAppSettings'

export type RequestParams = Record<
string,
string | string[] | number | boolean
> | void
import { RequestParams, parameterizeRoute } from '@siafoundation/request'

export type RequestConfig<Payload, Result> = {
swr?: SWROptions<Result>
Expand Down Expand Up @@ -238,28 +234,6 @@ export function buildAxiosConfig<Params extends RequestParams, Payload, Result>(
} as AxiosRequestConfig<Payload>
}

function parameterizeRoute(
route: string | null,
params: RequestParams
): string | null {
if (route && params) {
const paramKeys = Object.keys(params)
for (const key of paramKeys) {
const value = String(params[key])
if (route.includes(`:${key}`)) {
route = route.replace(`:${key}`, value)
} else {
if (!route.includes('?')) {
route += `?${key}=${encodeURIComponent(value)}`
} else {
route += `&${key}=${encodeURIComponent(value)}`
}
}
}
}
return route
}

export function buildRouteWithParams<
Params extends RequestParams,
Payload,
Expand Down
12 changes: 12 additions & 0 deletions libs/request/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"presets": [
[
"@nx/react/babel",
{
"runtime": "automatic",
"useBuiltIns": "usage"
}
]
],
"plugins": []
}
21 changes: 21 additions & 0 deletions libs/request/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": ["plugin:@nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"rules": {
"@nx/dependency-checks": [
"error",
{
"ignoredFiles": ["libs/request/rollup.config.js"]
}
]
},
"overrides": [
{
"files": ["*.json"],
"parser": "jsonc-eslint-parser",
"rules": {
"@nx/dependency-checks": "error"
}
}
]
}
3 changes: 3 additions & 0 deletions libs/request/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# request

Core library for building request APIs.
17 changes: 17 additions & 0 deletions libs/request/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */
export default {
displayName: 'request',
preset: '../../jest.preset.js',
transform: {
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
'^.+\\.[tj]sx?$': [
'babel-jest',
{
presets: ['@nx/next/babel'],
plugins: ['@babel/plugin-transform-private-methods'],
},
],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/request',
}
10 changes: 10 additions & 0 deletions libs/request/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@siafoundation/request",
"description": "Core library for building request APIs.",
"version": "0.0.0",
"license": "MIT",
"dependencies": {
"axios": "^0.27.2"
},
"types": "./src/index.d.ts"
}
42 changes: 42 additions & 0 deletions libs/request/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "request",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/request/src",
"projectType": "library",
"tags": [],
"targets": {
"build": {
"executor": "@nx/rollup:rollup",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/request",
"tsConfig": "libs/request/tsconfig.lib.json",
"project": "libs/request/package.json",
"entryFile": "libs/request/src/index.ts",
"external": ["react/jsx-runtime"],
"compiler": "tsc",
"outputFileName": "index.js",
"rollupConfig": "libs/request/rollup.config.js",
"assets": [
{
"glob": "libs/request/*.md",
"input": ".",
"output": "."
}
]
},
"configurations": {}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"]
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/libs/request"],
"options": {
"jestConfig": "libs/request/jest.config.ts"
}
}
}
}
18 changes: 18 additions & 0 deletions libs/request/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const preserveDirectives = require('rollup-plugin-preserve-directives')

// https://github.com/rollup/rollup/issues/4699#issuecomment-1465302665
function getRollupOptions(options) {
return {
...options,
output: {
...options.output,
preserveModules: true,
format: 'esm',
sourcemap: true,
},
plugins: options.plugins.concat(preserveDirectives.default()),
}
}

module.exports = getRollupOptions
67 changes: 67 additions & 0 deletions libs/request/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Axios } from 'axios'

export type RequestParams = Record<
string,
string | string[] | number | boolean
> | void

export function parameterizeRoute(
route: string | null,
params: RequestParams
): string | null {
if (route && params) {
const paramKeys = Object.keys(params)
for (const key of paramKeys) {
const value = String(params[key])
if (route.includes(`:${key}`)) {
route = route.replace(`:${key}`, value)
} else {
if (!route.includes('?')) {
route += `?${key}=${encodeURIComponent(value)}`
} else {
route += `&${key}=${encodeURIComponent(value)}`
}
}
}
}
return route
}

export function buildRequestHandler<
Params = void,
Payload = void,
Response = void
>(
axios: Axios,
method: 'get' | 'post' | 'patch' | 'put' | 'delete',
route: string
) {
type ParamsArg = Params extends void
? Record<string, never>
: { params: Params }
type PayloadArg = Payload extends void
? Record<string, never>
: { payload: Payload }

return (
...args: Params extends void
? Payload extends void
? []
: [PayloadArg]
: [
ParamsArg &
(Payload extends void
? Record<string, never>
: { payload?: Payload })
]
) => {
const arg = args[0] || {}
const paramRoute =
'params' in arg
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
parameterizeRoute(route, arg.params as RequestParams)!
: route
const payload = 'payload' in arg ? arg.payload : undefined
return axios[method]<Response>(paramRoute, payload)
}
}
25 changes: 25 additions & 0 deletions libs/request/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
22 changes: 22 additions & 0 deletions libs/request/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": [
"node",
"@nx/react/typings/cssmodule.d.ts",
"@nx/react/typings/image.d.ts"
]
},
"exclude": [
"**/*.spec.ts",
"**/*.test.ts",
"**/*.spec.tsx",
"**/*.test.tsx",
"**/*.spec.js",
"**/*.test.js",
"**/*.spec.jsx",
"**/*.test.jsx"
],
"include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"]
}
19 changes: 19 additions & 0 deletions libs/request/tsconfig.spec.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"include": [
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.test.tsx",
"src/**/*.spec.tsx",
"src/**/*.test.js",
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx",
"src/**/*.d.ts"
]
}
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {
"@siafoundation/request": ["libs/request/src/index.ts"],
"@siafoundation/data-sources": ["libs/data-sources/src/index.ts"],
"@siafoundation/design-system": ["libs/design-system/src/index.ts"],
"@siafoundation/fonts": ["libs/fonts/src/index.ts"],
Expand Down

0 comments on commit 68261fb

Please sign in to comment.