Simplify the typing of workerRequests.ts

This commit is contained in:
Sam Rose 2024-02-15 15:49:30 +00:00
parent dde8f77877
commit e4b0330866
No known key found for this signature in database
2 changed files with 37 additions and 45 deletions

View File

@ -1,22 +1,14 @@
import { HeaderInit, Headers } from "node-fetch"
import { Header } from "../../constants" import { Header } from "../../constants"
const correlator = require("correlation-id") const correlator = require("correlation-id")
export const setHeader = (headers: HeaderInit) => { export const setHeader = (headers: Record<string, string>) => {
const correlationId = correlator.getId() const correlationId = correlator.getId()
if (!correlationId) { if (!correlationId) {
return return
} }
if (headers instanceof Headers) {
headers.set(Header.CORRELATION_ID, correlationId)
} else if (Array.isArray(headers)) {
headers.push([Header.CORRELATION_ID, correlationId])
} else {
headers[Header.CORRELATION_ID] = correlationId headers[Header.CORRELATION_ID] = correlationId
} }
}
export function getId() { export function getId() {
return correlator.getId() return correlator.getId()

View File

@ -38,15 +38,24 @@ function ensureHeadersIsObject(headers: HeadersInit | undefined): Headers {
return headersObj return headersObj
} }
export function request(request: RequestInit & { ctx?: Ctx }): RequestInit { interface Request {
const ctx = request.ctx ctx?: Ctx
request.headers = ensureHeadersIsObject(request.headers) method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"
headers?: { [key: string]: string }
if (!ctx) { body?: { [key: string]: any }
if (coreEnv.INTERNAL_API_KEY) {
request.headers.set(constants.Header.API_KEY, coreEnv.INTERNAL_API_KEY)
} }
} else if (ctx.headers) {
export function createRequest(request: Request): RequestInit {
const headers: Record<string, string> = {}
const requestInit: RequestInit = {
method: request.method,
}
const ctx = request.ctx
if (!ctx && coreEnv.INTERNAL_API_KEY) {
headers[constants.Header.API_KEY] = coreEnv.INTERNAL_API_KEY
} else if (ctx && ctx.headers) {
// copy all Budibase utilised headers over - copying everything can have // copy all Budibase utilised headers over - copying everything can have
// side effects like requests being rejected due to odd content types etc // side effects like requests being rejected due to odd content types etc
for (let header of Object.values(constants.Header)) { for (let header of Object.values(constants.Header)) {
@ -56,34 +65,25 @@ export function request(request: RequestInit & { ctx?: Ctx }): RequestInit {
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
for (let v of value) { headers[header] = value[0]
request.headers.append(header, v)
}
} else { } else {
request.headers.set(header, value) headers[header] = value
} }
} }
} }
// apply tenancy if its available // apply tenancy if its available
if (tenancy.isTenantIdSet()) { if (tenancy.isTenantIdSet()) {
request.headers.set(constants.Header.TENANT_ID, tenancy.getTenantId()) headers[constants.Header.TENANT_ID] = tenancy.getTenantId()
} }
if (request.body && Object.keys(request.body).length > 0) { if (request.body && Object.keys(request.body).length > 0) {
request.headers.set("Content-Type", "application/json") headers["Content-Type"] = "application/json"
request.body = requestInit.body = JSON.stringify(request.body)
typeof request.body === "object"
? JSON.stringify(request.body)
: request.body
} else {
delete request.body
} }
// add x-budibase-correlation-id header logging.correlation.setHeader(headers)
logging.correlation.setHeader(request.headers) return requestInit
delete request.ctx
return request
} }
async function checkResponse( async function checkResponse(
@ -132,9 +132,9 @@ export async function sendSmtpEmail({
// tenant ID will be set in header // tenant ID will be set in header
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + `/api/global/email/send`), checkSlashesInUrl(env.WORKER_URL + `/api/global/email/send`),
request({ createRequest({
method: "POST", method: "POST",
body: JSON.stringify({ body: {
email: to, email: to,
from, from,
contents, contents,
@ -144,7 +144,7 @@ export async function sendSmtpEmail({
purpose: "custom", purpose: "custom",
automation, automation,
invite, invite,
}), },
}) })
) )
return checkResponse(response, "send email") return checkResponse(response, "send email")
@ -154,7 +154,7 @@ export async function removeAppFromUserRoles(ctx: Ctx, appId: string) {
const prodAppId = dbCore.getProdAppID(appId) const prodAppId = dbCore.getProdAppID(appId)
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + `/api/global/roles/${prodAppId}`), checkSlashesInUrl(env.WORKER_URL + `/api/global/roles/${prodAppId}`),
request({ createRequest({
ctx, ctx,
method: "DELETE", method: "DELETE",
}) })
@ -166,7 +166,7 @@ export async function allGlobalUsers(ctx: Ctx) {
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + "/api/global/users"), checkSlashesInUrl(env.WORKER_URL + "/api/global/users"),
// we don't want to use API key when getting self // we don't want to use API key when getting self
request({ ctx, method: "GET" }) createRequest({ ctx, method: "GET" })
) )
return checkResponse(response, "get users", { ctx }) return checkResponse(response, "get users", { ctx })
} }
@ -175,7 +175,7 @@ export async function saveGlobalUser(ctx: Ctx) {
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + "/api/global/users"), checkSlashesInUrl(env.WORKER_URL + "/api/global/users"),
// we don't want to use API key when getting self // we don't want to use API key when getting self
request({ ctx, method: "POST", body: ctx.request.body }) createRequest({ ctx, method: "POST", body: ctx.request.body })
) )
return checkResponse(response, "save user", { ctx }) return checkResponse(response, "save user", { ctx })
} }
@ -186,7 +186,7 @@ export async function deleteGlobalUser(ctx: Ctx) {
env.WORKER_URL + `/api/global/users/${ctx.params.userId}` env.WORKER_URL + `/api/global/users/${ctx.params.userId}`
), ),
// we don't want to use API key when getting self // we don't want to use API key when getting self
request({ ctx, method: "DELETE" }) createRequest({ ctx, method: "DELETE" })
) )
return checkResponse(response, "delete user", { ctx }) return checkResponse(response, "delete user", { ctx })
} }
@ -197,7 +197,7 @@ export async function readGlobalUser(ctx: Ctx): Promise<User> {
env.WORKER_URL + `/api/global/users/${ctx.params.userId}` env.WORKER_URL + `/api/global/users/${ctx.params.userId}`
), ),
// we don't want to use API key when getting self // we don't want to use API key when getting self
request({ ctx, method: "GET" }) createRequest({ ctx, method: "GET" })
) )
return checkResponse(response, "get user", { ctx }) return checkResponse(response, "get user", { ctx })
} }
@ -207,7 +207,7 @@ export async function getChecklist(): Promise<{
}> { }> {
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + "/api/global/configs/checklist"), checkSlashesInUrl(env.WORKER_URL + "/api/global/configs/checklist"),
request({ method: "GET" }) createRequest({ method: "GET" })
) )
return checkResponse(response, "get checklist") return checkResponse(response, "get checklist")
} }
@ -215,7 +215,7 @@ export async function getChecklist(): Promise<{
export async function generateApiKey(userId: string) { export async function generateApiKey(userId: string) {
const response = await fetch( const response = await fetch(
checkSlashesInUrl(env.WORKER_URL + "/api/global/self/api_key"), checkSlashesInUrl(env.WORKER_URL + "/api/global/self/api_key"),
request({ method: "POST", body: JSON.stringify({ userId }) }) createRequest({ method: "POST", body: { userId } })
) )
return checkResponse(response, "generate API key") return checkResponse(response, "generate API key")
} }