From c307801dbab5a01c715f1ed26e27e1f334ade0ac Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 15:44:43 +0000 Subject: [PATCH 1/7] fix: update API code to use Axios instance --- site/src/api/api.ts | 447 +++++++++++++++++++++++++++----------------- 1 file changed, 271 insertions(+), 176 deletions(-) diff --git a/site/src/api/api.ts b/site/src/api/api.ts index a243123a310f3..3acbeffbfd960 100644 --- a/site/src/api/api.ts +++ b/site/src/api/api.ts @@ -1,20 +1,36 @@ /** - * @fileoverview This file is imported externally by things like vscode-coder so - * it must not import anything using aliases otherwise it will break when being - * imported by those external consumers. For example, `utils/delay` must be - * imported using `../utils/delay` instead. + * @file Coder is starting to import the Coder API file into more and more + * external projects, as a "pseudo-SDK". We are not at a stage where we are + * ready to commit to maintaing a public SDK, but we need equivalent + * functionality in other places. + * + * Message somebody from Team Blueberry if you need more context, but so far, + * these projects are importing the file: + * + * - The Coder VS Code extension + * @see {@link https://github.com/coder/vscode-coder} + * - The Coder Backstage plugin + * @see {@link https://github.com/coder/backstage-plugins} + * + * It is important that this file not do any aliased imports, or else the other + * consumers could break (particularly for platforms that limit how much you can + * touch their configuration files, like Backstage). Relative imports are still + * safe, though. + * + * For example, `utils/delay` must be imported using `../utils/delay` instead. */ - -import axios, { isAxiosError } from "axios"; +import globalAxios, { isAxiosError } from "axios"; import type dayjs from "dayjs"; import userAgentParser from "ua-parser-js"; import { delay } from "../utils/delay"; import * as TypesGen from "./typesGenerated"; +export const coderAxiosInstance = globalAxios.create(); + // Adds 304 for the default axios validateStatus function // https://github.com/axios/axios#handling-errors Check status here // https://httpstatusdogs.com/ -axios.defaults.validateStatus = (status) => { +coderAxiosInstance.defaults.validateStatus = (status) => { return (status >= 200 && status < 300) || status === 304; }; @@ -27,7 +43,7 @@ export const hardCodedCSRFCookie = (): string => { // "JXm9hOUdZctWt0ZZGAy9xiS/gxMKYOThdxjjMnMUyn4=" const csrfToken = "KNKvagCBEHZK7ihe2t7fj6VeJ0UyTDco1yVUJE8N06oNqxLu5Zx1vRxZbgfC0mJJgeGkVjgs08mgPbcWPBkZ1A=="; - axios.defaults.headers.common["X-CSRF-TOKEN"] = csrfToken; + coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = csrfToken; return csrfToken; }; @@ -59,10 +75,11 @@ const token = if (token !== null && token.getAttribute("content") !== null) { if (process.env.NODE_ENV === "development") { // Development mode uses a hard-coded CSRF token - axios.defaults.headers.common["X-CSRF-TOKEN"] = hardCodedCSRFCookie(); + coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = + hardCodedCSRFCookie(); token.setAttribute("content", hardCodedCSRFCookie()); } else { - axios.defaults.headers.common["X-CSRF-TOKEN"] = + coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = token.getAttribute("content") ?? ""; } } else { @@ -73,11 +90,11 @@ if (token !== null && token.getAttribute("content") !== null) { } export const setSessionToken = (token: string) => { - axios.defaults.headers.common["Coder-Session-Token"] = token; + coderAxiosInstance.defaults.headers.common["Coder-Session-Token"] = token; }; export const setHost = (host?: string) => { - axios.defaults.baseURL = host; + coderAxiosInstance.defaults.baseURL = host; }; const CONTENT_TYPE_JSON = { @@ -114,50 +131,53 @@ export const login = async ( password, }); - const response = await axios.post( - "/api/v2/users/login", - payload, - { - headers: { ...CONTENT_TYPE_JSON }, - }, - ); + const response = + await coderAxiosInstance.post( + "/api/v2/users/login", + payload, + { + headers: { ...CONTENT_TYPE_JSON }, + }, + ); return response.data; }; export const convertToOAUTH = async (request: TypesGen.ConvertLoginRequest) => { - const response = await axios.post( - "/api/v2/users/me/convert-login", - request, - ); + const response = + await coderAxiosInstance.post( + "/api/v2/users/me/convert-login", + request, + ); return response.data; }; export const logout = async (): Promise => { - await axios.post("/api/v2/users/logout"); + await coderAxiosInstance.post("/api/v2/users/logout"); }; export const getAuthenticatedUser = async () => { - const response = await axios.get("/api/v2/users/me"); + const response = + await coderAxiosInstance.get("/api/v2/users/me"); return response.data; }; export const getUserParameters = async (templateID: string) => { - const response = await axios.get( + const response = await coderAxiosInstance.get( "/api/v2/users/me/autofill-parameters?template_id=" + templateID, ); return response.data; }; export const getAuthMethods = async (): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( "/api/v2/users/authmethods", ); return response.data; }; export const getUserLoginType = async (): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( "/api/v2/users/me/login-type", ); return response.data; @@ -166,24 +186,26 @@ export const getUserLoginType = async (): Promise => { export const checkAuthorization = async ( params: TypesGen.AuthorizationRequest, ): Promise => { - const response = await axios.post( - `/api/v2/authcheck`, - params, - ); + const response = + await coderAxiosInstance.post( + `/api/v2/authcheck`, + params, + ); return response.data; }; export const getApiKey = async (): Promise => { - const response = await axios.post( - "/api/v2/users/me/keys", - ); + const response = + await coderAxiosInstance.post( + "/api/v2/users/me/keys", + ); return response.data; }; export const getTokens = async ( params: TypesGen.TokensFilter, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/users/me/keys/tokens`, { params, @@ -193,18 +215,23 @@ export const getTokens = async ( }; export const deleteToken = async (keyId: string): Promise => { - await axios.delete("/api/v2/users/me/keys/" + keyId); + await coderAxiosInstance.delete("/api/v2/users/me/keys/" + keyId); }; export const createToken = async ( params: TypesGen.CreateTokenRequest, ): Promise => { - const response = await axios.post(`/api/v2/users/me/keys/tokens`, params); + const response = await coderAxiosInstance.post( + `/api/v2/users/me/keys/tokens`, + params, + ); return response.data; }; export const getTokenConfig = async (): Promise => { - const response = await axios.get("/api/v2/users/me/keys/tokens/tokenconfig"); + const response = await coderAxiosInstance.get( + "/api/v2/users/me/keys/tokens/tokenconfig", + ); return response.data; }; @@ -213,23 +240,26 @@ export const getUsers = async ( signal?: AbortSignal, ): Promise => { const url = getURLWithSearchParams("/api/v2/users", options); - const response = await axios.get(url.toString(), { - signal, - }); + const response = await coderAxiosInstance.get( + url.toString(), + { + signal, + }, + ); return response.data; }; export const getOrganization = async ( organizationId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}`, ); return response.data; }; export const getOrganizations = async (): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( "/api/v2/users/me/organizations", ); return response.data; @@ -238,7 +268,7 @@ export const getOrganizations = async (): Promise => { export const getTemplate = async ( templateId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templates/${templateId}`, ); return response.data; @@ -260,7 +290,7 @@ export const getTemplates = async ( params["deprecated"] = String(options.deprecated); } - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/templates`, { params, @@ -273,7 +303,7 @@ export const getTemplateByName = async ( organizationId: string, name: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${name}`, ); return response.data; @@ -282,7 +312,7 @@ export const getTemplateByName = async ( export const getTemplateVersion = async ( versionId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templateversions/${versionId}`, ); return response.data; @@ -291,7 +321,7 @@ export const getTemplateVersion = async ( export const getTemplateVersionResources = async ( versionId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templateversions/${versionId}/resources`, ); return response.data; @@ -300,16 +330,16 @@ export const getTemplateVersionResources = async ( export const getTemplateVersionVariables = async ( versionId: string, ): Promise => { - const response = await axios.get( - `/api/v2/templateversions/${versionId}/variables`, - ); + const response = await coderAxiosInstance.get< + TypesGen.TemplateVersionVariable[] + >(`/api/v2/templateversions/${versionId}/variables`); return response.data; }; export const getTemplateVersions = async ( templateId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templates/${templateId}/versions`, ); return response.data; @@ -320,7 +350,7 @@ export const getTemplateVersionByName = async ( templateName: string, versionName: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${templateName}/versions/${versionName}`, ); return response.data; @@ -336,7 +366,7 @@ export const getPreviousTemplateVersionByName = async ( versionName: string, ) => { try { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${templateName}/versions/${versionName}/previous`, ); return response.data; @@ -344,7 +374,7 @@ export const getPreviousTemplateVersionByName = async ( // When there is no previous version, like the first version of a template, // the API returns 404 so in this case we can safely return undefined if ( - axios.isAxiosError(error) && + isAxiosError(error) && error.response && error.response.status === 404 ) { @@ -359,7 +389,7 @@ export const createTemplateVersion = async ( organizationId: string, data: TypesGen.CreateTemplateVersionRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/organizations/${organizationId}/templateversions`, data, ); @@ -369,7 +399,7 @@ export const createTemplateVersion = async ( export const getTemplateVersionExternalAuth = async ( versionId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templateversions/${versionId}/external-auth`, ); return response.data; @@ -378,7 +408,7 @@ export const getTemplateVersionExternalAuth = async ( export const getTemplateVersionRichParameters = async ( versionId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templateversions/${versionId}/rich-parameters`, ); return response.data; @@ -388,7 +418,7 @@ export const createTemplate = async ( organizationId: string, data: TypesGen.CreateTemplateRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/organizations/${organizationId}/templates`, data, ); @@ -399,7 +429,7 @@ export const updateActiveTemplateVersion = async ( templateId: string, data: TypesGen.UpdateActiveTemplateVersion, ) => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/templates/${templateId}/versions`, data, ); @@ -410,7 +440,7 @@ export const patchTemplateVersion = async ( templateVersionId: string, data: TypesGen.PatchTemplateVersionRequest, ) => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/templateversions/${templateVersionId}`, data, ); @@ -418,14 +448,14 @@ export const patchTemplateVersion = async ( }; export const archiveTemplateVersion = async (templateVersionId: string) => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/templateversions/${templateVersionId}/archive`, ); return response.data; }; export const unarchiveTemplateVersion = async (templateVersionId: string) => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/templateversions/${templateVersionId}/unarchive`, ); return response.data; @@ -435,7 +465,7 @@ export const updateTemplateMeta = async ( templateId: string, data: TypesGen.UpdateTemplateMeta, ): Promise => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/templates/${templateId}`, data, ); @@ -450,7 +480,7 @@ export const updateTemplateMeta = async ( export const deleteTemplate = async ( templateId: string, ): Promise => { - const response = await axios.delete( + const response = await coderAxiosInstance.delete( `/api/v2/templates/${templateId}`, ); return response.data; @@ -460,7 +490,7 @@ export const getWorkspace = async ( workspaceId: string, params?: TypesGen.WorkspaceOptions, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspaces/${workspaceId}`, { params, @@ -509,7 +539,8 @@ export const getWorkspaces = async ( options: TypesGen.WorkspacesRequest, ): Promise => { const url = getURLWithSearchParams("/api/v2/workspaces", options); - const response = await axios.get(url); + const response = + await coderAxiosInstance.get(url); return response.data; }; @@ -518,7 +549,7 @@ export const getWorkspaceByOwnerAndName = async ( workspaceName: string, params?: TypesGen.WorkspaceOptions, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/users/${username}/workspace/${workspaceName}`, { params, @@ -560,7 +591,7 @@ export const postWorkspaceBuild = async ( workspaceId: string, data: TypesGen.CreateWorkspaceBuildRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/workspaces/${workspaceId}/builds`, data, ); @@ -605,7 +636,7 @@ export const deleteWorkspace = ( export const cancelWorkspaceBuild = async ( workspaceBuildId: TypesGen.WorkspaceBuild["id"], ): Promise => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/workspacebuilds/${workspaceBuildId}/cancel`, ); return response.data; @@ -619,7 +650,7 @@ export const updateWorkspaceDormancy = async ( dormant: dormant, }; - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/workspaces/${workspaceId}/dormant`, data, ); @@ -634,7 +665,7 @@ export const updateWorkspaceAutomaticUpdates = async ( automatic_updates: automaticUpdates, }; - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/workspaces/${workspaceId}/autoupdates`, req, ); @@ -668,7 +699,7 @@ export const restartWorkspace = async ({ export const cancelTemplateVersionBuild = async ( templateVersionId: TypesGen.TemplateVersion["id"], ): Promise => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/templateversions/${templateVersionId}/cancel`, ); return response.data; @@ -677,7 +708,10 @@ export const cancelTemplateVersionBuild = async ( export const createUser = async ( user: TypesGen.CreateUserRequest, ): Promise => { - const response = await axios.post("/api/v2/users", user); + const response = await coderAxiosInstance.post( + "/api/v2/users", + user, + ); return response.data; }; @@ -686,7 +720,7 @@ export const createWorkspace = async ( userId = "me", workspace: TypesGen.CreateWorkspaceRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/organizations/${organizationId}/members/${userId}/workspaces`, workspace, ); @@ -697,17 +731,17 @@ export const patchWorkspace = async ( workspaceId: string, data: TypesGen.UpdateWorkspaceRequest, ) => { - await axios.patch(`/api/v2/workspaces/${workspaceId}`, data); + await coderAxiosInstance.patch(`/api/v2/workspaces/${workspaceId}`, data); }; export const getBuildInfo = async (): Promise => { - const response = await axios.get("/api/v2/buildinfo"); + const response = await coderAxiosInstance.get("/api/v2/buildinfo"); return response.data; }; export const getUpdateCheck = async (): Promise => { - const response = await axios.get("/api/v2/updatecheck"); + const response = await coderAxiosInstance.get("/api/v2/updatecheck"); return response.data; }; @@ -716,9 +750,13 @@ export const putWorkspaceAutostart = async ( autostart: TypesGen.UpdateWorkspaceAutostartRequest, ): Promise => { const payload = JSON.stringify(autostart); - await axios.put(`/api/v2/workspaces/${workspaceID}/autostart`, payload, { - headers: { ...CONTENT_TYPE_JSON }, - }); + await coderAxiosInstance.put( + `/api/v2/workspaces/${workspaceID}/autostart`, + payload, + { + headers: { ...CONTENT_TYPE_JSON }, + }, + ); }; export const putWorkspaceAutostop = async ( @@ -726,16 +764,23 @@ export const putWorkspaceAutostop = async ( ttl: TypesGen.UpdateWorkspaceTTLRequest, ): Promise => { const payload = JSON.stringify(ttl); - await axios.put(`/api/v2/workspaces/${workspaceID}/ttl`, payload, { - headers: { ...CONTENT_TYPE_JSON }, - }); + await coderAxiosInstance.put( + `/api/v2/workspaces/${workspaceID}/ttl`, + payload, + { + headers: { ...CONTENT_TYPE_JSON }, + }, + ); }; export const updateProfile = async ( userId: string, data: TypesGen.UpdateUserProfileRequest, ): Promise => { - const response = await axios.put(`/api/v2/users/${userId}/profile`, data); + const response = await coderAxiosInstance.put( + `/api/v2/users/${userId}/profile`, + data, + ); return response.data; }; @@ -743,14 +788,19 @@ export const updateAppearanceSettings = async ( userId: string, data: TypesGen.UpdateUserAppearanceSettingsRequest, ): Promise => { - const response = await axios.put(`/api/v2/users/${userId}/appearance`, data); + const response = await coderAxiosInstance.put( + `/api/v2/users/${userId}/appearance`, + data, + ); return response.data; }; export const getUserQuietHoursSchedule = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await axios.get(`/api/v2/users/${userId}/quiet-hours`); + const response = await coderAxiosInstance.get( + `/api/v2/users/${userId}/quiet-hours`, + ); return response.data; }; @@ -758,14 +808,17 @@ export const updateUserQuietHoursSchedule = async ( userId: TypesGen.User["id"], data: TypesGen.UpdateUserQuietHoursScheduleRequest, ): Promise => { - const response = await axios.put(`/api/v2/users/${userId}/quiet-hours`, data); + const response = await coderAxiosInstance.put( + `/api/v2/users/${userId}/quiet-hours`, + data, + ); return response.data; }; export const activateUser = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/users/${userId}/status/activate`, ); return response.data; @@ -774,7 +827,7 @@ export const activateUser = async ( export const suspendUser = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/users/${userId}/status/suspend`, ); return response.data; @@ -783,7 +836,7 @@ export const suspendUser = async ( export const deleteUser = async ( userId: TypesGen.User["id"], ): Promise => { - return await axios.delete(`/api/v2/users/${userId}`); + return await coderAxiosInstance.delete(`/api/v2/users/${userId}`); }; // API definition: @@ -791,11 +844,11 @@ export const deleteUser = async ( export const hasFirstUser = async (): Promise => { try { // If it is success, it is true - await axios.get("/api/v2/users/first"); + await coderAxiosInstance.get("/api/v2/users/first"); return true; } catch (error) { // If it returns a 404, it is false - if (axios.isAxiosError(error) && error.response?.status === 404) { + if (isAxiosError(error) && error.response?.status === 404) { return false; } @@ -806,7 +859,7 @@ export const hasFirstUser = async (): Promise => { export const createFirstUser = async ( req: TypesGen.CreateFirstUserRequest, ): Promise => { - const response = await axios.post(`/api/v2/users/first`, req); + const response = await coderAxiosInstance.post(`/api/v2/users/first`, req); return response.data; }; @@ -814,11 +867,13 @@ export const updateUserPassword = async ( userId: TypesGen.User["id"], updatePassword: TypesGen.UpdateUserPasswordRequest, ): Promise => - axios.put(`/api/v2/users/${userId}/password`, updatePassword); + coderAxiosInstance.put(`/api/v2/users/${userId}/password`, updatePassword); export const getRoles = async (): Promise> => { const response = - await axios.get>(`/api/v2/users/roles`); + await coderAxiosInstance.get>( + `/api/v2/users/roles`, + ); return response.data; }; @@ -826,7 +881,7 @@ export const updateUserRoles = async ( roles: TypesGen.Role["name"][], userId: TypesGen.User["id"], ): Promise => { - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/users/${userId}/roles`, { roles }, ); @@ -836,7 +891,7 @@ export const updateUserRoles = async ( export const getUserSSHKey = async ( userId = "me", ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/users/${userId}/gitsshkey`, ); return response.data; @@ -845,7 +900,7 @@ export const getUserSSHKey = async ( export const regenerateUserSSHKey = async ( userId = "me", ): Promise => { - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/users/${userId}/gitsshkey`, ); return response.data; @@ -855,7 +910,7 @@ export const getWorkspaceBuilds = async ( workspaceId: string, req?: TypesGen.WorkspaceBuildsRequest, ) => { - const response = await axios.get( + const response = await coderAxiosInstance.get( getURLWithSearchParams(`/api/v2/workspaces/${workspaceId}/builds`, req), ); return response.data; @@ -866,7 +921,7 @@ export const getWorkspaceBuildByNumber = async ( workspaceName: string, buildNumber: number, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/users/${username}/workspace/${workspaceName}/builds/${buildNumber}`, ); return response.data; @@ -876,7 +931,7 @@ export const getWorkspaceBuildLogs = async ( buildId: string, before: Date, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspacebuilds/${buildId}/logs?before=${before.getTime()}`, ); return response.data; @@ -885,7 +940,7 @@ export const getWorkspaceBuildLogs = async ( export const getWorkspaceAgentLogs = async ( agentID: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspaceagents/${agentID}/logs`, ); return response.data; @@ -895,21 +950,21 @@ export const putWorkspaceExtension = async ( workspaceId: string, newDeadline: dayjs.Dayjs, ): Promise => { - await axios.put(`/api/v2/workspaces/${workspaceId}/extend`, { + await coderAxiosInstance.put(`/api/v2/workspaces/${workspaceId}/extend`, { deadline: newDeadline, }); }; export const refreshEntitlements = async (): Promise => { - await axios.post("/api/v2/licenses/refresh-entitlements"); + await coderAxiosInstance.post("/api/v2/licenses/refresh-entitlements"); }; export const getEntitlements = async (): Promise => { try { - const response = await axios.get("/api/v2/entitlements"); + const response = await coderAxiosInstance.get("/api/v2/entitlements"); return response.data; } catch (ex) { - if (axios.isAxiosError(ex) && ex.response?.status === 404) { + if (isAxiosError(ex) && ex.response?.status === 404) { return { errors: [], features: withDefaultFeatures({}), @@ -926,10 +981,10 @@ export const getEntitlements = async (): Promise => { export const getExperiments = async (): Promise => { try { - const response = await axios.get("/api/v2/experiments"); + const response = await coderAxiosInstance.get("/api/v2/experiments"); return response.data; } catch (error) { - if (axios.isAxiosError(error) && error.response?.status === 404) { + if (isAxiosError(error) && error.response?.status === 404) { return []; } throw error; @@ -939,10 +994,12 @@ export const getExperiments = async (): Promise => { export const getAvailableExperiments = async (): Promise => { try { - const response = await axios.get("/api/v2/experiments/available"); + const response = await coderAxiosInstance.get( + "/api/v2/experiments/available", + ); return response.data; } catch (error) { - if (axios.isAxiosError(error) && error.response?.status === 404) { + if (isAxiosError(error) && error.response?.status === 404) { return { safe: [] }; } throw error; @@ -952,14 +1009,18 @@ export const getAvailableExperiments = export const getExternalAuthProvider = async ( provider: string, ): Promise => { - const resp = await axios.get(`/api/v2/external-auth/${provider}`); + const resp = await coderAxiosInstance.get( + `/api/v2/external-auth/${provider}`, + ); return resp.data; }; export const getExternalAuthDevice = async ( provider: string, ): Promise => { - const resp = await axios.get(`/api/v2/external-auth/${provider}/device`); + const resp = await coderAxiosInstance.get( + `/api/v2/external-auth/${provider}/device`, + ); return resp.data; }; @@ -967,7 +1028,7 @@ export const exchangeExternalAuthDevice = async ( provider: string, req: TypesGen.ExternalAuthDeviceExchange, ): Promise => { - const resp = await axios.post( + const resp = await coderAxiosInstance.post( `/api/v2/external-auth/${provider}/device`, req, ); @@ -976,14 +1037,16 @@ export const exchangeExternalAuthDevice = async ( export const getUserExternalAuthProviders = async (): Promise => { - const resp = await axios.get(`/api/v2/external-auth`); + const resp = await coderAxiosInstance.get(`/api/v2/external-auth`); return resp.data; }; export const unlinkExternalAuthProvider = async ( provider: string, ): Promise => { - const resp = await axios.delete(`/api/v2/external-auth/${provider}`); + const resp = await coderAxiosInstance.delete( + `/api/v2/external-auth/${provider}`, + ); return resp.data; }; @@ -993,21 +1056,28 @@ export const getOAuth2ProviderApps = async ( const params = filter?.user_id ? new URLSearchParams({ user_id: filter.user_id }) : ""; - const resp = await axios.get(`/api/v2/oauth2-provider/apps?${params}`); + const resp = await coderAxiosInstance.get( + `/api/v2/oauth2-provider/apps?${params}`, + ); return resp.data; }; export const getOAuth2ProviderApp = async ( id: string, ): Promise => { - const resp = await axios.get(`/api/v2/oauth2-provider/apps/${id}`); + const resp = await coderAxiosInstance.get( + `/api/v2/oauth2-provider/apps/${id}`, + ); return resp.data; }; export const postOAuth2ProviderApp = async ( data: TypesGen.PostOAuth2ProviderAppRequest, ): Promise => { - const response = await axios.post(`/api/v2/oauth2-provider/apps`, data); + const response = await coderAxiosInstance.post( + `/api/v2/oauth2-provider/apps`, + data, + ); return response.data; }; @@ -1015,25 +1085,32 @@ export const putOAuth2ProviderApp = async ( id: string, data: TypesGen.PutOAuth2ProviderAppRequest, ): Promise => { - const response = await axios.put(`/api/v2/oauth2-provider/apps/${id}`, data); + const response = await coderAxiosInstance.put( + `/api/v2/oauth2-provider/apps/${id}`, + data, + ); return response.data; }; export const deleteOAuth2ProviderApp = async (id: string): Promise => { - await axios.delete(`/api/v2/oauth2-provider/apps/${id}`); + await coderAxiosInstance.delete(`/api/v2/oauth2-provider/apps/${id}`); }; export const getOAuth2ProviderAppSecrets = async ( id: string, ): Promise => { - const resp = await axios.get(`/api/v2/oauth2-provider/apps/${id}/secrets`); + const resp = await coderAxiosInstance.get( + `/api/v2/oauth2-provider/apps/${id}/secrets`, + ); return resp.data; }; export const postOAuth2ProviderAppSecret = async ( id: string, ): Promise => { - const resp = await axios.post(`/api/v2/oauth2-provider/apps/${id}/secrets`); + const resp = await coderAxiosInstance.post( + `/api/v2/oauth2-provider/apps/${id}/secrets`, + ); return resp.data; }; @@ -1041,27 +1118,29 @@ export const deleteOAuth2ProviderAppSecret = async ( appId: string, secretId: string, ): Promise => { - await axios.delete( + await coderAxiosInstance.delete( `/api/v2/oauth2-provider/apps/${appId}/secrets/${secretId}`, ); }; export const revokeOAuth2ProviderApp = async (appId: string): Promise => { - await axios.delete(`/oauth2/tokens?client_id=${appId}`); + await coderAxiosInstance.delete(`/oauth2/tokens?client_id=${appId}`); }; export const getAuditLogs = async ( options: TypesGen.AuditLogsRequest, ): Promise => { const url = getURLWithSearchParams("/api/v2/audit", options); - const response = await axios.get(url); + const response = await coderAxiosInstance.get(url); return response.data; }; export const getTemplateDAUs = async ( templateId: string, ): Promise => { - const response = await axios.get(`/api/v2/templates/${templateId}/daus`); + const response = await coderAxiosInstance.get( + `/api/v2/templates/${templateId}/daus`, + ); return response.data; }; @@ -1071,7 +1150,9 @@ export const getDeploymentDAUs = async ( // we truncate the tz offset down to the closest hour. offset = Math.trunc(new Date().getTimezoneOffset() / 60), ): Promise => { - const response = await axios.get(`/api/v2/insights/daus?tz_offset=${offset}`); + const response = await coderAxiosInstance.get( + `/api/v2/insights/daus?tz_offset=${offset}`, + ); return response.data; }; @@ -1083,14 +1164,16 @@ export const getTemplateACLAvailable = async ( `/api/v2/templates/${templateId}/acl/available`, options, ); - const response = await axios.get(url.toString()); + const response = await coderAxiosInstance.get(url.toString()); return response.data; }; export const getTemplateACL = async ( templateId: string, ): Promise => { - const response = await axios.get(`/api/v2/templates/${templateId}/acl`); + const response = await coderAxiosInstance.get( + `/api/v2/templates/${templateId}/acl`, + ); return response.data; }; @@ -1098,7 +1181,7 @@ export const updateTemplateACL = async ( templateId: string, data: TypesGen.UpdateTemplateACL, ): Promise<{ message: string }> => { - const response = await axios.patch( + const response = await coderAxiosInstance.patch( `/api/v2/templates/${templateId}/acl`, data, ); @@ -1107,14 +1190,14 @@ export const updateTemplateACL = async ( export const getApplicationsHost = async (): Promise => { - const response = await axios.get(`/api/v2/applications/host`); + const response = await coderAxiosInstance.get(`/api/v2/applications/host`); return response.data; }; export const getGroups = async ( organizationId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/groups`, ); return response.data; @@ -1124,7 +1207,7 @@ export const createGroup = async ( organizationId: string, data: TypesGen.CreateGroupRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/organizations/${organizationId}/groups`, data, ); @@ -1132,7 +1215,7 @@ export const createGroup = async ( }; export const getGroup = async (groupId: string): Promise => { - const response = await axios.get(`/api/v2/groups/${groupId}`); + const response = await coderAxiosInstance.get(`/api/v2/groups/${groupId}`); return response.data; }; @@ -1140,7 +1223,10 @@ export const patchGroup = async ( groupId: string, data: TypesGen.PatchGroupRequest, ): Promise => { - const response = await axios.patch(`/api/v2/groups/${groupId}`, data); + const response = await coderAxiosInstance.patch( + `/api/v2/groups/${groupId}`, + data, + ); return response.data; }; @@ -1162,13 +1248,13 @@ export const removeMember = async (groupId: string, userId: string) => { }; export const deleteGroup = async (groupId: string): Promise => { - await axios.delete(`/api/v2/groups/${groupId}`); + await coderAxiosInstance.delete(`/api/v2/groups/${groupId}`); }; export const getWorkspaceQuota = async ( username: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspace-quota/${encodeURIComponent(username)}`, ); return response.data; @@ -1177,7 +1263,7 @@ export const getWorkspaceQuota = async ( export const getAgentListeningPorts = async ( agentID: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspaceagents/${agentID}/listening-ports`, ); return response.data; @@ -1186,7 +1272,7 @@ export const getAgentListeningPorts = async ( export const getWorkspaceAgentSharedPorts = async ( workspaceID: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspaces/${workspaceID}/port-share`, ); return response.data; @@ -1196,7 +1282,7 @@ export const upsertWorkspaceAgentSharedPort = async ( workspaceID: string, req: TypesGen.UpsertWorkspaceAgentPortShareRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( `/api/v2/workspaces/${workspaceID}/port-share`, req, ); @@ -1207,7 +1293,7 @@ export const deleteWorkspaceAgentSharedPort = async ( workspaceID: string, req: TypesGen.DeleteWorkspaceAgentPortShareRequest, ): Promise => { - const response = await axios.delete( + const response = await coderAxiosInstance.delete( `/api/v2/workspaces/${workspaceID}/port-share`, { data: req, @@ -1219,7 +1305,7 @@ export const deleteWorkspaceAgentSharedPort = async ( // getDeploymentSSHConfig is used by the VSCode-Extension. export const getDeploymentSSHConfig = async (): Promise => { - const response = await axios.get(`/api/v2/deployment/ssh`); + const response = await coderAxiosInstance.get(`/api/v2/deployment/ssh`); return response.data; }; @@ -1229,25 +1315,28 @@ export type DeploymentConfig = { }; export const getDeploymentConfig = async (): Promise => { - const response = await axios.get(`/api/v2/deployment/config`); + const response = await coderAxiosInstance.get(`/api/v2/deployment/config`); return response.data; }; export const getDeploymentStats = async (): Promise => { - const response = await axios.get(`/api/v2/deployment/stats`); + const response = await coderAxiosInstance.get(`/api/v2/deployment/stats`); return response.data; }; export const getReplicas = async (): Promise => { - const response = await axios.get(`/api/v2/replicas`); + const response = await coderAxiosInstance.get(`/api/v2/replicas`); return response.data; }; export const getFile = async (fileId: string): Promise => { - const response = await axios.get(`/api/v2/files/${fileId}`, { - responseType: "arraybuffer", - }); + const response = await coderAxiosInstance.get( + `/api/v2/files/${fileId}`, + { + responseType: "arraybuffer", + }, + ); return response.data; }; @@ -1255,7 +1344,7 @@ export const getWorkspaceProxyRegions = async (): Promise< TypesGen.RegionsResponse > => { const response = - await axios.get>( + await coderAxiosInstance.get>( `/api/v2/regions`, ); return response.data; @@ -1264,7 +1353,7 @@ export const getWorkspaceProxyRegions = async (): Promise< export const getWorkspaceProxies = async (): Promise< TypesGen.RegionsResponse > => { - const response = await axios.get< + const response = await coderAxiosInstance.get< TypesGen.RegionsResponse >(`/api/v2/workspaceproxies`); return response.data; @@ -1273,16 +1362,16 @@ export const getWorkspaceProxies = async (): Promise< export const createWorkspaceProxy = async ( b: TypesGen.CreateWorkspaceProxyRequest, ): Promise => { - const response = await axios.post(`/api/v2/workspaceproxies`, b); + const response = await coderAxiosInstance.post(`/api/v2/workspaceproxies`, b); return response.data; }; export const getAppearance = async (): Promise => { try { - const response = await axios.get(`/api/v2/appearance`); + const response = await coderAxiosInstance.get(`/api/v2/appearance`); return response.data || {}; } catch (ex) { - if (axios.isAxiosError(ex) && ex.response?.status === 404) { + if (isAxiosError(ex) && ex.response?.status === 404) { return { application_name: "", logo_url: "", @@ -1298,14 +1387,14 @@ export const getAppearance = async (): Promise => { export const updateAppearance = async ( b: TypesGen.AppearanceConfig, ): Promise => { - const response = await axios.put(`/api/v2/appearance`, b); + const response = await coderAxiosInstance.put(`/api/v2/appearance`, b); return response.data; }; export const getTemplateExamples = async ( organizationId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/organizations/${organizationId}/templates/examples`, ); return response.data; @@ -1314,7 +1403,7 @@ export const getTemplateExamples = async ( export const uploadFile = async ( file: File, ): Promise => { - const response = await axios.post("/api/v2/files", file, { + const response = await coderAxiosInstance.post("/api/v2/files", file, { headers: { "Content-Type": "application/x-tar", }, @@ -1325,7 +1414,7 @@ export const uploadFile = async ( export const getTemplateVersionLogs = async ( versionId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/templateversions/${versionId}/logs`, ); return response.data; @@ -1341,9 +1430,9 @@ export const updateWorkspaceVersion = async ( export const getWorkspaceBuildParameters = async ( workspaceBuildId: TypesGen.WorkspaceBuild["id"], ): Promise => { - const response = await axios.get( - `/api/v2/workspacebuilds/${workspaceBuildId}/parameters`, - ); + const response = await coderAxiosInstance.get< + TypesGen.WorkspaceBuildParameter[] + >(`/api/v2/workspacebuilds/${workspaceBuildId}/parameters`); return response.data; }; type Claims = { @@ -1363,19 +1452,19 @@ export type GetLicensesResponse = Omit & { }; export const getLicenses = async (): Promise => { - const response = await axios.get(`/api/v2/licenses`); + const response = await coderAxiosInstance.get(`/api/v2/licenses`); return response.data; }; export const createLicense = async ( data: TypesGen.AddLicenseRequest, ): Promise => { - const response = await axios.post(`/api/v2/licenses`, data); + const response = await coderAxiosInstance.post(`/api/v2/licenses`, data); return response.data; }; export const removeLicense = async (licenseId: number): Promise => { - await axios.delete(`/api/v2/licenses/${licenseId}`); + await coderAxiosInstance.delete(`/api/v2/licenses/${licenseId}`); }; export class MissingBuildParameters extends Error { @@ -1467,7 +1556,7 @@ export const updateWorkspace = async ( export const getWorkspaceResolveAutostart = async ( workspaceId: string, ): Promise => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/workspaces/${workspaceId}/resolve-autostart`, ); return response.data; @@ -1677,7 +1766,7 @@ export const watchBuildLogsByBuildId = ( export const issueReconnectingPTYSignedToken = async ( params: TypesGen.IssueReconnectingPTYSignedTokenRequest, ): Promise => { - const response = await axios.post( + const response = await coderAxiosInstance.post( "/api/v2/applications/reconnecting-pty-signed-token", params, ); @@ -1706,7 +1795,9 @@ export const getInsightsUserLatency = async ( filters: InsightsParams, ): Promise => { const params = new URLSearchParams(filters); - const response = await axios.get(`/api/v2/insights/user-latency?${params}`); + const response = await coderAxiosInstance.get( + `/api/v2/insights/user-latency?${params}`, + ); return response.data; }; @@ -1714,7 +1805,9 @@ export const getInsightsUserActivity = async ( filters: InsightsParams, ): Promise => { const params = new URLSearchParams(filters); - const response = await axios.get(`/api/v2/insights/user-activity?${params}`); + const response = await coderAxiosInstance.get( + `/api/v2/insights/user-activity?${params}`, + ); return response.data; }; @@ -1726,7 +1819,7 @@ export const getInsightsTemplate = async ( params: InsightsTemplateParams, ): Promise => { const searchParams = new URLSearchParams(params); - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/insights/templates?${searchParams}`, ); return response.data; @@ -1734,7 +1827,7 @@ export const getInsightsTemplate = async ( export const getHealth = async (force: boolean = false) => { const params = new URLSearchParams({ force: force.toString() }); - const response = await axios.get( + const response = await coderAxiosInstance.get( `/api/v2/debug/health?${params}`, ); return response.data; @@ -1742,14 +1835,16 @@ export const getHealth = async (force: boolean = false) => { export const getHealthSettings = async () => { return ( - await axios.get(`/api/v2/debug/health/settings`) + await coderAxiosInstance.get( + `/api/v2/debug/health/settings`, + ) ).data; }; export const updateHealthSettings = async ( data: TypesGen.UpdateHealthSettings, ) => { - const response = await axios.put( + const response = await coderAxiosInstance.put( `/api/v2/debug/health/settings`, data, ); @@ -1757,11 +1852,11 @@ export const updateHealthSettings = async ( }; export const putFavoriteWorkspace = async (workspaceID: string) => { - await axios.put(`/api/v2/workspaces/${workspaceID}/favorite`); + await coderAxiosInstance.put(`/api/v2/workspaces/${workspaceID}/favorite`); }; export const deleteFavoriteWorkspace = async (workspaceID: string) => { - await axios.delete(`/api/v2/workspaces/${workspaceID}/favorite`); + await coderAxiosInstance.delete(`/api/v2/workspaces/${workspaceID}/favorite`); }; export type GetJFrogXRayScanParams = { @@ -1776,7 +1871,7 @@ export const getJFrogXRayScan = async (options: GetJFrogXRayScanParams) => { }); try { - const res = await axios.get( + const res = await coderAxiosInstance.get( `/api/v2/integrations/jfrog/xray-scan?${searchParams}`, ); return res.data; From 7faaf2e4541bd597337bc18533a71d36d3e07859 Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 15:48:43 +0000 Subject: [PATCH 2/7] docs: fix typo --- site/src/api/api.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/site/src/api/api.ts b/site/src/api/api.ts index 3acbeffbfd960..f33b4a17b1ce5 100644 --- a/site/src/api/api.ts +++ b/site/src/api/api.ts @@ -1,7 +1,7 @@ /** * @file Coder is starting to import the Coder API file into more and more * external projects, as a "pseudo-SDK". We are not at a stage where we are - * ready to commit to maintaing a public SDK, but we need equivalent + * ready to commit to maintaining a public SDK, but we need equivalent * functionality in other places. * * Message somebody from Team Blueberry if you need more context, but so far, From c2298756d9eca8f47c984c04b3b8f63778907e4b Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 16:30:42 +0000 Subject: [PATCH 3/7] fix: update all global axios imports to use Coder instance --- site/e2e/helpers.ts | 4 ++-- site/e2e/reporter.ts | 5 +++-- site/src/api/api.test.ts | 22 ++++++++++++++-------- site/src/api/errors.ts | 5 +++-- site/src/contexts/auth/RequireAuth.tsx | 9 +++++---- site/src/contexts/useProxyLatency.ts | 4 ++-- 6 files changed, 29 insertions(+), 20 deletions(-) diff --git a/site/e2e/helpers.ts b/site/e2e/helpers.ts index 26e416cad7158..d73c5a92e53fc 100644 --- a/site/e2e/helpers.ts +++ b/site/e2e/helpers.ts @@ -1,5 +1,5 @@ import { type BrowserContext, expect, type Page, test } from "@playwright/test"; -import axios from "axios"; +import { coderAxiosInstance } from "api/api"; import { type ChildProcess, exec, spawn } from "child_process"; import { randomUUID } from "crypto"; import express from "express"; @@ -398,7 +398,7 @@ export const waitUntilUrlIsNotResponding = async (url: string) => { while (retries < maxRetries) { try { - await axios.get(url); + await coderAxiosInstance.get(url); } catch (error) { return; } diff --git a/site/e2e/reporter.ts b/site/e2e/reporter.ts index fe214d8aed41d..ccc61af600877 100644 --- a/site/e2e/reporter.ts +++ b/site/e2e/reporter.ts @@ -8,7 +8,7 @@ import type { Reporter, TestError, } from "@playwright/test/reporter"; -import axios from "axios"; +import { coderAxiosInstance } from "api/api"; import * as fs from "fs/promises"; import type { Writable } from "stream"; import { coderdPProfPort, enterpriseLicense } from "./constants"; @@ -136,9 +136,10 @@ class CoderReporter implements Reporter { const logLines = (chunk: string): string[] => chunk.trimEnd().split("\n"); const exportDebugPprof = async (outputFile: string) => { - const response = await axios.get( + const response = await coderAxiosInstance.get( `http://127.0.0.1:${coderdPProfPort}/debug/pprof/goroutine?debug=1`, ); + if (response.status !== 200) { throw new Error(`Error: Received status code ${response.status}`); } diff --git a/site/src/api/api.test.ts b/site/src/api/api.test.ts index e755d241cbec5..7d37d1c5b3f00 100644 --- a/site/src/api/api.test.ts +++ b/site/src/api/api.test.ts @@ -1,4 +1,3 @@ -import axios from "axios"; import { MockTemplate, MockTemplateVersionParameter1, @@ -8,6 +7,7 @@ import { MockWorkspaceBuildParameter1, } from "testHelpers/entities"; import * as api from "./api"; +import { coderAxiosInstance } from "./api"; import type * as TypesGen from "./typesGenerated"; describe("api.ts", () => { @@ -17,13 +17,16 @@ describe("api.ts", () => { const loginResponse: TypesGen.LoginWithPasswordResponse = { session_token: "abc_123_test", }; - jest.spyOn(axios, "post").mockResolvedValueOnce({ data: loginResponse }); + + jest + .spyOn(coderAxiosInstance, "post") + .mockResolvedValueOnce({ data: loginResponse }); // when const result = await api.login("test", "123"); // then - expect(axios.post).toHaveBeenCalled(); + expect(coderAxiosInstance.post).toHaveBeenCalled(); expect(result).toStrictEqual(loginResponse); }); @@ -38,7 +41,7 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.reject(expectedError); }); - axios.post = axiosMockPost; + coderAxiosInstance.post = axiosMockPost; try { await api.login("test", "123"); @@ -54,7 +57,7 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.resolve(); }); - axios.post = axiosMockPost; + coderAxiosInstance.post = axiosMockPost; // when await api.logout(); @@ -73,7 +76,8 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.reject(expectedError); }); - axios.post = axiosMockPost; + + coderAxiosInstance.post = axiosMockPost; try { await api.logout(); @@ -92,7 +96,8 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.resolve({ data: apiKeyResponse }); }); - axios.post = axiosMockPost; + + coderAxiosInstance.post = axiosMockPost; // when const result = await api.getApiKey(); @@ -112,7 +117,8 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.reject(expectedError); }); - axios.post = axiosMockPost; + + coderAxiosInstance.post = axiosMockPost; try { await api.getApiKey(); diff --git a/site/src/api/errors.ts b/site/src/api/errors.ts index 0d1a3dc203e5b..3bd38b0262ff1 100644 --- a/site/src/api/errors.ts +++ b/site/src/api/errors.ts @@ -1,4 +1,5 @@ -import axios, { type AxiosError, type AxiosResponse } from "axios"; +import { type AxiosError, type AxiosResponse, isAxiosError } from "axios"; +import { coderAxiosInstance } from "./api"; const Language = { errorsByCode: { @@ -25,7 +26,7 @@ export type ApiError = AxiosError & { export const isApiError = (err: unknown): err is ApiError => { return ( - axios.isAxiosError(err) && + isAxiosError(err) && err.response !== undefined && isApiErrorResponse(err.response.data) ); diff --git a/site/src/contexts/auth/RequireAuth.tsx b/site/src/contexts/auth/RequireAuth.tsx index 4ec918eed134b..b7a2ea2a05131 100644 --- a/site/src/contexts/auth/RequireAuth.tsx +++ b/site/src/contexts/auth/RequireAuth.tsx @@ -1,4 +1,4 @@ -import axios from "axios"; +import { coderAxiosInstance } from "api/api"; import { type FC, useEffect } from "react"; import { Outlet, Navigate, useLocation } from "react-router-dom"; import { isApiError } from "api/errors"; @@ -22,7 +22,7 @@ export const RequireAuth: FC = () => { return; } - const interceptorHandle = axios.interceptors.response.use( + const interceptorHandle = coderAxiosInstance.interceptors.response.use( (okResponse) => okResponse, (error: unknown) => { // 401 Unauthorized @@ -32,13 +32,14 @@ export const RequireAuth: FC = () => { signOut(); } - // Otherwise, pass the response through so that it can be displayed in the UI + // Otherwise, pass the response through so that it can be displayed in + // the UI return Promise.reject(error); }, ); return () => { - axios.interceptors.response.eject(interceptorHandle); + coderAxiosInstance.interceptors.response.eject(interceptorHandle); }; }, [isLoading, isSigningOut, isSignedIn, signOut]); diff --git a/site/src/contexts/useProxyLatency.ts b/site/src/contexts/useProxyLatency.ts index 9d28830b7de20..3f1f59c628ada 100644 --- a/site/src/contexts/useProxyLatency.ts +++ b/site/src/contexts/useProxyLatency.ts @@ -1,5 +1,5 @@ import PerformanceObserver from "@fastly/performance-observer-polyfill"; -import axios from "axios"; +import { coderAxiosInstance } from "api/api"; import { useEffect, useReducer, useState } from "react"; import type { Region } from "api/typesGenerated"; import { generateRandomString } from "utils/random"; @@ -198,7 +198,7 @@ export const useProxyLatency = ( observer.observe({ entryTypes: ["resource"] }); const proxyRequests = Object.keys(proxyChecks).map((latencyURL) => { - return axios.get(latencyURL, { + return coderAxiosInstance.get(latencyURL, { withCredentials: false, // Must add a custom header to make the request not a "simple request". // We want to force a preflight request. From 9dc88d7c54ff5a3ec2b5329a16dabc84c277af78 Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 16:34:23 +0000 Subject: [PATCH 4/7] fix: remove needless import --- site/src/api/errors.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/site/src/api/errors.ts b/site/src/api/errors.ts index 3bd38b0262ff1..ada591d754fb2 100644 --- a/site/src/api/errors.ts +++ b/site/src/api/errors.ts @@ -1,5 +1,4 @@ import { type AxiosError, type AxiosResponse, isAxiosError } from "axios"; -import { coderAxiosInstance } from "./api"; const Language = { errorsByCode: { From 2bad193cc4eb33a81cf765f723e2fddac8de940a Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 16:51:06 +0000 Subject: [PATCH 5/7] fix: update import order --- site/e2e/helpers.ts | 2 +- site/e2e/reporter.ts | 2 +- site/src/contexts/auth/RequireAuth.tsx | 2 +- site/src/contexts/useProxyLatency.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/site/e2e/helpers.ts b/site/e2e/helpers.ts index d73c5a92e53fc..a524bf6e8c73a 100644 --- a/site/e2e/helpers.ts +++ b/site/e2e/helpers.ts @@ -1,5 +1,4 @@ import { type BrowserContext, expect, type Page, test } from "@playwright/test"; -import { coderAxiosInstance } from "api/api"; import { type ChildProcess, exec, spawn } from "child_process"; import { randomUUID } from "crypto"; import express from "express"; @@ -7,6 +6,7 @@ import capitalize from "lodash/capitalize"; import path from "path"; import * as ssh from "ssh2"; import { Duplex } from "stream"; +import { coderAxiosInstance } from "api/api"; import type { WorkspaceBuildParameter, UpdateTemplateMeta, diff --git a/site/e2e/reporter.ts b/site/e2e/reporter.ts index ccc61af600877..d4bceb306ef8d 100644 --- a/site/e2e/reporter.ts +++ b/site/e2e/reporter.ts @@ -8,9 +8,9 @@ import type { Reporter, TestError, } from "@playwright/test/reporter"; -import { coderAxiosInstance } from "api/api"; import * as fs from "fs/promises"; import type { Writable } from "stream"; +import { coderAxiosInstance } from "api/api"; import { coderdPProfPort, enterpriseLicense } from "./constants"; class CoderReporter implements Reporter { diff --git a/site/src/contexts/auth/RequireAuth.tsx b/site/src/contexts/auth/RequireAuth.tsx index b7a2ea2a05131..72114ecd51437 100644 --- a/site/src/contexts/auth/RequireAuth.tsx +++ b/site/src/contexts/auth/RequireAuth.tsx @@ -1,6 +1,6 @@ -import { coderAxiosInstance } from "api/api"; import { type FC, useEffect } from "react"; import { Outlet, Navigate, useLocation } from "react-router-dom"; +import { coderAxiosInstance } from "api/api"; import { isApiError } from "api/errors"; import { Loader } from "components/Loader/Loader"; import { ProxyProvider } from "contexts/ProxyContext"; diff --git a/site/src/contexts/useProxyLatency.ts b/site/src/contexts/useProxyLatency.ts index 3f1f59c628ada..f474c997ff0c3 100644 --- a/site/src/contexts/useProxyLatency.ts +++ b/site/src/contexts/useProxyLatency.ts @@ -1,6 +1,6 @@ import PerformanceObserver from "@fastly/performance-observer-polyfill"; -import { coderAxiosInstance } from "api/api"; import { useEffect, useReducer, useState } from "react"; +import { coderAxiosInstance } from "api/api"; import type { Region } from "api/typesGenerated"; import { generateRandomString } from "utils/random"; From a3da329da1ca73110e8a2d0ca51f6090a02c9734 Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Mon, 22 Apr 2024 19:17:21 +0000 Subject: [PATCH 6/7] refactor: rename coderAxiosInstance to axiosInstance --- site/e2e/helpers.ts | 4 +- site/e2e/reporter.ts | 4 +- site/src/api/api.test.ts | 16 +- site/src/api/api.ts | 339 ++++++++++++------------- site/src/contexts/auth/RequireAuth.tsx | 6 +- site/src/contexts/useProxyLatency.ts | 4 +- 6 files changed, 176 insertions(+), 197 deletions(-) diff --git a/site/e2e/helpers.ts b/site/e2e/helpers.ts index a524bf6e8c73a..1c5349fbf5e5b 100644 --- a/site/e2e/helpers.ts +++ b/site/e2e/helpers.ts @@ -6,7 +6,7 @@ import capitalize from "lodash/capitalize"; import path from "path"; import * as ssh from "ssh2"; import { Duplex } from "stream"; -import { coderAxiosInstance } from "api/api"; +import { axiosInstance } from "api/api"; import type { WorkspaceBuildParameter, UpdateTemplateMeta, @@ -398,7 +398,7 @@ export const waitUntilUrlIsNotResponding = async (url: string) => { while (retries < maxRetries) { try { - await coderAxiosInstance.get(url); + await axiosInstance.get(url); } catch (error) { return; } diff --git a/site/e2e/reporter.ts b/site/e2e/reporter.ts index d4bceb306ef8d..f981dede78e66 100644 --- a/site/e2e/reporter.ts +++ b/site/e2e/reporter.ts @@ -10,7 +10,7 @@ import type { } from "@playwright/test/reporter"; import * as fs from "fs/promises"; import type { Writable } from "stream"; -import { coderAxiosInstance } from "api/api"; +import { axiosInstance } from "api/api"; import { coderdPProfPort, enterpriseLicense } from "./constants"; class CoderReporter implements Reporter { @@ -136,7 +136,7 @@ class CoderReporter implements Reporter { const logLines = (chunk: string): string[] => chunk.trimEnd().split("\n"); const exportDebugPprof = async (outputFile: string) => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `http://127.0.0.1:${coderdPProfPort}/debug/pprof/goroutine?debug=1`, ); diff --git a/site/src/api/api.test.ts b/site/src/api/api.test.ts index 7d37d1c5b3f00..18615306683c4 100644 --- a/site/src/api/api.test.ts +++ b/site/src/api/api.test.ts @@ -7,7 +7,7 @@ import { MockWorkspaceBuildParameter1, } from "testHelpers/entities"; import * as api from "./api"; -import { coderAxiosInstance } from "./api"; +import { axiosInstance } from "./api"; import type * as TypesGen from "./typesGenerated"; describe("api.ts", () => { @@ -19,14 +19,14 @@ describe("api.ts", () => { }; jest - .spyOn(coderAxiosInstance, "post") + .spyOn(axiosInstance, "post") .mockResolvedValueOnce({ data: loginResponse }); // when const result = await api.login("test", "123"); // then - expect(coderAxiosInstance.post).toHaveBeenCalled(); + expect(axiosInstance.post).toHaveBeenCalled(); expect(result).toStrictEqual(loginResponse); }); @@ -41,7 +41,7 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.reject(expectedError); }); - coderAxiosInstance.post = axiosMockPost; + axiosInstance.post = axiosMockPost; try { await api.login("test", "123"); @@ -57,7 +57,7 @@ describe("api.ts", () => { const axiosMockPost = jest.fn().mockImplementationOnce(() => { return Promise.resolve(); }); - coderAxiosInstance.post = axiosMockPost; + axiosInstance.post = axiosMockPost; // when await api.logout(); @@ -77,7 +77,7 @@ describe("api.ts", () => { return Promise.reject(expectedError); }); - coderAxiosInstance.post = axiosMockPost; + axiosInstance.post = axiosMockPost; try { await api.logout(); @@ -97,7 +97,7 @@ describe("api.ts", () => { return Promise.resolve({ data: apiKeyResponse }); }); - coderAxiosInstance.post = axiosMockPost; + axiosInstance.post = axiosMockPost; // when const result = await api.getApiKey(); @@ -118,7 +118,7 @@ describe("api.ts", () => { return Promise.reject(expectedError); }); - coderAxiosInstance.post = axiosMockPost; + axiosInstance.post = axiosMockPost; try { await api.getApiKey(); diff --git a/site/src/api/api.ts b/site/src/api/api.ts index f33b4a17b1ce5..6b4102073b3d1 100644 --- a/site/src/api/api.ts +++ b/site/src/api/api.ts @@ -25,12 +25,12 @@ import userAgentParser from "ua-parser-js"; import { delay } from "../utils/delay"; import * as TypesGen from "./typesGenerated"; -export const coderAxiosInstance = globalAxios.create(); +export const axiosInstance = globalAxios.create(); // Adds 304 for the default axios validateStatus function // https://github.com/axios/axios#handling-errors Check status here // https://httpstatusdogs.com/ -coderAxiosInstance.defaults.validateStatus = (status) => { +axiosInstance.defaults.validateStatus = (status) => { return (status >= 200 && status < 300) || status === 304; }; @@ -43,7 +43,7 @@ export const hardCodedCSRFCookie = (): string => { // "JXm9hOUdZctWt0ZZGAy9xiS/gxMKYOThdxjjMnMUyn4=" const csrfToken = "KNKvagCBEHZK7ihe2t7fj6VeJ0UyTDco1yVUJE8N06oNqxLu5Zx1vRxZbgfC0mJJgeGkVjgs08mgPbcWPBkZ1A=="; - coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = csrfToken; + axiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = csrfToken; return csrfToken; }; @@ -75,11 +75,11 @@ const token = if (token !== null && token.getAttribute("content") !== null) { if (process.env.NODE_ENV === "development") { // Development mode uses a hard-coded CSRF token - coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = + axiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = hardCodedCSRFCookie(); token.setAttribute("content", hardCodedCSRFCookie()); } else { - coderAxiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = + axiosInstance.defaults.headers.common["X-CSRF-TOKEN"] = token.getAttribute("content") ?? ""; } } else { @@ -90,11 +90,11 @@ if (token !== null && token.getAttribute("content") !== null) { } export const setSessionToken = (token: string) => { - coderAxiosInstance.defaults.headers.common["Coder-Session-Token"] = token; + axiosInstance.defaults.headers.common["Coder-Session-Token"] = token; }; export const setHost = (host?: string) => { - coderAxiosInstance.defaults.baseURL = host; + axiosInstance.defaults.baseURL = host; }; const CONTENT_TYPE_JSON = { @@ -131,53 +131,50 @@ export const login = async ( password, }); - const response = - await coderAxiosInstance.post( - "/api/v2/users/login", - payload, - { - headers: { ...CONTENT_TYPE_JSON }, - }, - ); + const response = await axiosInstance.post( + "/api/v2/users/login", + payload, + { + headers: { ...CONTENT_TYPE_JSON }, + }, + ); return response.data; }; export const convertToOAUTH = async (request: TypesGen.ConvertLoginRequest) => { - const response = - await coderAxiosInstance.post( - "/api/v2/users/me/convert-login", - request, - ); + const response = await axiosInstance.post( + "/api/v2/users/me/convert-login", + request, + ); return response.data; }; export const logout = async (): Promise => { - await coderAxiosInstance.post("/api/v2/users/logout"); + await axiosInstance.post("/api/v2/users/logout"); }; export const getAuthenticatedUser = async () => { - const response = - await coderAxiosInstance.get("/api/v2/users/me"); + const response = await axiosInstance.get("/api/v2/users/me"); return response.data; }; export const getUserParameters = async (templateID: string) => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( "/api/v2/users/me/autofill-parameters?template_id=" + templateID, ); return response.data; }; export const getAuthMethods = async (): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( "/api/v2/users/authmethods", ); return response.data; }; export const getUserLoginType = async (): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( "/api/v2/users/me/login-type", ); return response.data; @@ -186,26 +183,24 @@ export const getUserLoginType = async (): Promise => { export const checkAuthorization = async ( params: TypesGen.AuthorizationRequest, ): Promise => { - const response = - await coderAxiosInstance.post( - `/api/v2/authcheck`, - params, - ); + const response = await axiosInstance.post( + `/api/v2/authcheck`, + params, + ); return response.data; }; export const getApiKey = async (): Promise => { - const response = - await coderAxiosInstance.post( - "/api/v2/users/me/keys", - ); + const response = await axiosInstance.post( + "/api/v2/users/me/keys", + ); return response.data; }; export const getTokens = async ( params: TypesGen.TokensFilter, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/users/me/keys/tokens`, { params, @@ -215,13 +210,13 @@ export const getTokens = async ( }; export const deleteToken = async (keyId: string): Promise => { - await coderAxiosInstance.delete("/api/v2/users/me/keys/" + keyId); + await axiosInstance.delete("/api/v2/users/me/keys/" + keyId); }; export const createToken = async ( params: TypesGen.CreateTokenRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/users/me/keys/tokens`, params, ); @@ -229,7 +224,7 @@ export const createToken = async ( }; export const getTokenConfig = async (): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( "/api/v2/users/me/keys/tokens/tokenconfig", ); return response.data; @@ -240,7 +235,7 @@ export const getUsers = async ( signal?: AbortSignal, ): Promise => { const url = getURLWithSearchParams("/api/v2/users", options); - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( url.toString(), { signal, @@ -252,14 +247,14 @@ export const getUsers = async ( export const getOrganization = async ( organizationId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}`, ); return response.data; }; export const getOrganizations = async (): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( "/api/v2/users/me/organizations", ); return response.data; @@ -268,7 +263,7 @@ export const getOrganizations = async (): Promise => { export const getTemplate = async ( templateId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templates/${templateId}`, ); return response.data; @@ -290,7 +285,7 @@ export const getTemplates = async ( params["deprecated"] = String(options.deprecated); } - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/templates`, { params, @@ -303,7 +298,7 @@ export const getTemplateByName = async ( organizationId: string, name: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${name}`, ); return response.data; @@ -312,7 +307,7 @@ export const getTemplateByName = async ( export const getTemplateVersion = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templateversions/${versionId}`, ); return response.data; @@ -321,7 +316,7 @@ export const getTemplateVersion = async ( export const getTemplateVersionResources = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templateversions/${versionId}/resources`, ); return response.data; @@ -330,16 +325,16 @@ export const getTemplateVersionResources = async ( export const getTemplateVersionVariables = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get< - TypesGen.TemplateVersionVariable[] - >(`/api/v2/templateversions/${versionId}/variables`); + const response = await axiosInstance.get( + `/api/v2/templateversions/${versionId}/variables`, + ); return response.data; }; export const getTemplateVersions = async ( templateId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templates/${templateId}/versions`, ); return response.data; @@ -350,7 +345,7 @@ export const getTemplateVersionByName = async ( templateName: string, versionName: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${templateName}/versions/${versionName}`, ); return response.data; @@ -366,7 +361,7 @@ export const getPreviousTemplateVersionByName = async ( versionName: string, ) => { try { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/templates/${templateName}/versions/${versionName}/previous`, ); return response.data; @@ -389,7 +384,7 @@ export const createTemplateVersion = async ( organizationId: string, data: TypesGen.CreateTemplateVersionRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/organizations/${organizationId}/templateversions`, data, ); @@ -399,7 +394,7 @@ export const createTemplateVersion = async ( export const getTemplateVersionExternalAuth = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templateversions/${versionId}/external-auth`, ); return response.data; @@ -408,7 +403,7 @@ export const getTemplateVersionExternalAuth = async ( export const getTemplateVersionRichParameters = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templateversions/${versionId}/rich-parameters`, ); return response.data; @@ -418,7 +413,7 @@ export const createTemplate = async ( organizationId: string, data: TypesGen.CreateTemplateRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/organizations/${organizationId}/templates`, data, ); @@ -429,7 +424,7 @@ export const updateActiveTemplateVersion = async ( templateId: string, data: TypesGen.UpdateActiveTemplateVersion, ) => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/templates/${templateId}/versions`, data, ); @@ -440,7 +435,7 @@ export const patchTemplateVersion = async ( templateVersionId: string, data: TypesGen.PatchTemplateVersionRequest, ) => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/templateversions/${templateVersionId}`, data, ); @@ -448,14 +443,14 @@ export const patchTemplateVersion = async ( }; export const archiveTemplateVersion = async (templateVersionId: string) => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/templateversions/${templateVersionId}/archive`, ); return response.data; }; export const unarchiveTemplateVersion = async (templateVersionId: string) => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/templateversions/${templateVersionId}/unarchive`, ); return response.data; @@ -465,7 +460,7 @@ export const updateTemplateMeta = async ( templateId: string, data: TypesGen.UpdateTemplateMeta, ): Promise => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/templates/${templateId}`, data, ); @@ -480,7 +475,7 @@ export const updateTemplateMeta = async ( export const deleteTemplate = async ( templateId: string, ): Promise => { - const response = await coderAxiosInstance.delete( + const response = await axiosInstance.delete( `/api/v2/templates/${templateId}`, ); return response.data; @@ -490,7 +485,7 @@ export const getWorkspace = async ( workspaceId: string, params?: TypesGen.WorkspaceOptions, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspaces/${workspaceId}`, { params, @@ -539,8 +534,7 @@ export const getWorkspaces = async ( options: TypesGen.WorkspacesRequest, ): Promise => { const url = getURLWithSearchParams("/api/v2/workspaces", options); - const response = - await coderAxiosInstance.get(url); + const response = await axiosInstance.get(url); return response.data; }; @@ -549,7 +543,7 @@ export const getWorkspaceByOwnerAndName = async ( workspaceName: string, params?: TypesGen.WorkspaceOptions, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/users/${username}/workspace/${workspaceName}`, { params, @@ -591,7 +585,7 @@ export const postWorkspaceBuild = async ( workspaceId: string, data: TypesGen.CreateWorkspaceBuildRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/workspaces/${workspaceId}/builds`, data, ); @@ -636,7 +630,7 @@ export const deleteWorkspace = ( export const cancelWorkspaceBuild = async ( workspaceBuildId: TypesGen.WorkspaceBuild["id"], ): Promise => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/workspacebuilds/${workspaceBuildId}/cancel`, ); return response.data; @@ -650,7 +644,7 @@ export const updateWorkspaceDormancy = async ( dormant: dormant, }; - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/workspaces/${workspaceId}/dormant`, data, ); @@ -665,7 +659,7 @@ export const updateWorkspaceAutomaticUpdates = async ( automatic_updates: automaticUpdates, }; - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/workspaces/${workspaceId}/autoupdates`, req, ); @@ -699,7 +693,7 @@ export const restartWorkspace = async ({ export const cancelTemplateVersionBuild = async ( templateVersionId: TypesGen.TemplateVersion["id"], ): Promise => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/templateversions/${templateVersionId}/cancel`, ); return response.data; @@ -708,7 +702,7 @@ export const cancelTemplateVersionBuild = async ( export const createUser = async ( user: TypesGen.CreateUserRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( "/api/v2/users", user, ); @@ -720,7 +714,7 @@ export const createWorkspace = async ( userId = "me", workspace: TypesGen.CreateWorkspaceRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/organizations/${organizationId}/members/${userId}/workspaces`, workspace, ); @@ -731,17 +725,17 @@ export const patchWorkspace = async ( workspaceId: string, data: TypesGen.UpdateWorkspaceRequest, ) => { - await coderAxiosInstance.patch(`/api/v2/workspaces/${workspaceId}`, data); + await axiosInstance.patch(`/api/v2/workspaces/${workspaceId}`, data); }; export const getBuildInfo = async (): Promise => { - const response = await coderAxiosInstance.get("/api/v2/buildinfo"); + const response = await axiosInstance.get("/api/v2/buildinfo"); return response.data; }; export const getUpdateCheck = async (): Promise => { - const response = await coderAxiosInstance.get("/api/v2/updatecheck"); + const response = await axiosInstance.get("/api/v2/updatecheck"); return response.data; }; @@ -750,7 +744,7 @@ export const putWorkspaceAutostart = async ( autostart: TypesGen.UpdateWorkspaceAutostartRequest, ): Promise => { const payload = JSON.stringify(autostart); - await coderAxiosInstance.put( + await axiosInstance.put( `/api/v2/workspaces/${workspaceID}/autostart`, payload, { @@ -764,20 +758,16 @@ export const putWorkspaceAutostop = async ( ttl: TypesGen.UpdateWorkspaceTTLRequest, ): Promise => { const payload = JSON.stringify(ttl); - await coderAxiosInstance.put( - `/api/v2/workspaces/${workspaceID}/ttl`, - payload, - { - headers: { ...CONTENT_TYPE_JSON }, - }, - ); + await axiosInstance.put(`/api/v2/workspaces/${workspaceID}/ttl`, payload, { + headers: { ...CONTENT_TYPE_JSON }, + }); }; export const updateProfile = async ( userId: string, data: TypesGen.UpdateUserProfileRequest, ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/profile`, data, ); @@ -788,7 +778,7 @@ export const updateAppearanceSettings = async ( userId: string, data: TypesGen.UpdateUserAppearanceSettingsRequest, ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/appearance`, data, ); @@ -798,7 +788,7 @@ export const updateAppearanceSettings = async ( export const getUserQuietHoursSchedule = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/users/${userId}/quiet-hours`, ); return response.data; @@ -808,7 +798,7 @@ export const updateUserQuietHoursSchedule = async ( userId: TypesGen.User["id"], data: TypesGen.UpdateUserQuietHoursScheduleRequest, ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/quiet-hours`, data, ); @@ -818,7 +808,7 @@ export const updateUserQuietHoursSchedule = async ( export const activateUser = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/status/activate`, ); return response.data; @@ -827,7 +817,7 @@ export const activateUser = async ( export const suspendUser = async ( userId: TypesGen.User["id"], ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/status/suspend`, ); return response.data; @@ -836,7 +826,7 @@ export const suspendUser = async ( export const deleteUser = async ( userId: TypesGen.User["id"], ): Promise => { - return await coderAxiosInstance.delete(`/api/v2/users/${userId}`); + return await axiosInstance.delete(`/api/v2/users/${userId}`); }; // API definition: @@ -844,7 +834,7 @@ export const deleteUser = async ( export const hasFirstUser = async (): Promise => { try { // If it is success, it is true - await coderAxiosInstance.get("/api/v2/users/first"); + await axiosInstance.get("/api/v2/users/first"); return true; } catch (error) { // If it returns a 404, it is false @@ -859,7 +849,7 @@ export const hasFirstUser = async (): Promise => { export const createFirstUser = async ( req: TypesGen.CreateFirstUserRequest, ): Promise => { - const response = await coderAxiosInstance.post(`/api/v2/users/first`, req); + const response = await axiosInstance.post(`/api/v2/users/first`, req); return response.data; }; @@ -867,11 +857,11 @@ export const updateUserPassword = async ( userId: TypesGen.User["id"], updatePassword: TypesGen.UpdateUserPasswordRequest, ): Promise => - coderAxiosInstance.put(`/api/v2/users/${userId}/password`, updatePassword); + axiosInstance.put(`/api/v2/users/${userId}/password`, updatePassword); export const getRoles = async (): Promise> => { const response = - await coderAxiosInstance.get>( + await axiosInstance.get>( `/api/v2/users/roles`, ); return response.data; @@ -881,7 +871,7 @@ export const updateUserRoles = async ( roles: TypesGen.Role["name"][], userId: TypesGen.User["id"], ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/roles`, { roles }, ); @@ -891,7 +881,7 @@ export const updateUserRoles = async ( export const getUserSSHKey = async ( userId = "me", ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/users/${userId}/gitsshkey`, ); return response.data; @@ -900,7 +890,7 @@ export const getUserSSHKey = async ( export const regenerateUserSSHKey = async ( userId = "me", ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/users/${userId}/gitsshkey`, ); return response.data; @@ -910,7 +900,7 @@ export const getWorkspaceBuilds = async ( workspaceId: string, req?: TypesGen.WorkspaceBuildsRequest, ) => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( getURLWithSearchParams(`/api/v2/workspaces/${workspaceId}/builds`, req), ); return response.data; @@ -921,7 +911,7 @@ export const getWorkspaceBuildByNumber = async ( workspaceName: string, buildNumber: number, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/users/${username}/workspace/${workspaceName}/builds/${buildNumber}`, ); return response.data; @@ -931,7 +921,7 @@ export const getWorkspaceBuildLogs = async ( buildId: string, before: Date, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspacebuilds/${buildId}/logs?before=${before.getTime()}`, ); return response.data; @@ -940,7 +930,7 @@ export const getWorkspaceBuildLogs = async ( export const getWorkspaceAgentLogs = async ( agentID: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspaceagents/${agentID}/logs`, ); return response.data; @@ -950,18 +940,18 @@ export const putWorkspaceExtension = async ( workspaceId: string, newDeadline: dayjs.Dayjs, ): Promise => { - await coderAxiosInstance.put(`/api/v2/workspaces/${workspaceId}/extend`, { + await axiosInstance.put(`/api/v2/workspaces/${workspaceId}/extend`, { deadline: newDeadline, }); }; export const refreshEntitlements = async (): Promise => { - await coderAxiosInstance.post("/api/v2/licenses/refresh-entitlements"); + await axiosInstance.post("/api/v2/licenses/refresh-entitlements"); }; export const getEntitlements = async (): Promise => { try { - const response = await coderAxiosInstance.get("/api/v2/entitlements"); + const response = await axiosInstance.get("/api/v2/entitlements"); return response.data; } catch (ex) { if (isAxiosError(ex) && ex.response?.status === 404) { @@ -981,7 +971,7 @@ export const getEntitlements = async (): Promise => { export const getExperiments = async (): Promise => { try { - const response = await coderAxiosInstance.get("/api/v2/experiments"); + const response = await axiosInstance.get("/api/v2/experiments"); return response.data; } catch (error) { if (isAxiosError(error) && error.response?.status === 404) { @@ -994,9 +984,7 @@ export const getExperiments = async (): Promise => { export const getAvailableExperiments = async (): Promise => { try { - const response = await coderAxiosInstance.get( - "/api/v2/experiments/available", - ); + const response = await axiosInstance.get("/api/v2/experiments/available"); return response.data; } catch (error) { if (isAxiosError(error) && error.response?.status === 404) { @@ -1009,16 +997,14 @@ export const getAvailableExperiments = export const getExternalAuthProvider = async ( provider: string, ): Promise => { - const resp = await coderAxiosInstance.get( - `/api/v2/external-auth/${provider}`, - ); + const resp = await axiosInstance.get(`/api/v2/external-auth/${provider}`); return resp.data; }; export const getExternalAuthDevice = async ( provider: string, ): Promise => { - const resp = await coderAxiosInstance.get( + const resp = await axiosInstance.get( `/api/v2/external-auth/${provider}/device`, ); return resp.data; @@ -1028,7 +1014,7 @@ export const exchangeExternalAuthDevice = async ( provider: string, req: TypesGen.ExternalAuthDeviceExchange, ): Promise => { - const resp = await coderAxiosInstance.post( + const resp = await axiosInstance.post( `/api/v2/external-auth/${provider}/device`, req, ); @@ -1037,16 +1023,14 @@ export const exchangeExternalAuthDevice = async ( export const getUserExternalAuthProviders = async (): Promise => { - const resp = await coderAxiosInstance.get(`/api/v2/external-auth`); + const resp = await axiosInstance.get(`/api/v2/external-auth`); return resp.data; }; export const unlinkExternalAuthProvider = async ( provider: string, ): Promise => { - const resp = await coderAxiosInstance.delete( - `/api/v2/external-auth/${provider}`, - ); + const resp = await axiosInstance.delete(`/api/v2/external-auth/${provider}`); return resp.data; }; @@ -1056,7 +1040,7 @@ export const getOAuth2ProviderApps = async ( const params = filter?.user_id ? new URLSearchParams({ user_id: filter.user_id }) : ""; - const resp = await coderAxiosInstance.get( + const resp = await axiosInstance.get( `/api/v2/oauth2-provider/apps?${params}`, ); return resp.data; @@ -1065,16 +1049,14 @@ export const getOAuth2ProviderApps = async ( export const getOAuth2ProviderApp = async ( id: string, ): Promise => { - const resp = await coderAxiosInstance.get( - `/api/v2/oauth2-provider/apps/${id}`, - ); + const resp = await axiosInstance.get(`/api/v2/oauth2-provider/apps/${id}`); return resp.data; }; export const postOAuth2ProviderApp = async ( data: TypesGen.PostOAuth2ProviderAppRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/oauth2-provider/apps`, data, ); @@ -1085,7 +1067,7 @@ export const putOAuth2ProviderApp = async ( id: string, data: TypesGen.PutOAuth2ProviderAppRequest, ): Promise => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/oauth2-provider/apps/${id}`, data, ); @@ -1093,13 +1075,13 @@ export const putOAuth2ProviderApp = async ( }; export const deleteOAuth2ProviderApp = async (id: string): Promise => { - await coderAxiosInstance.delete(`/api/v2/oauth2-provider/apps/${id}`); + await axiosInstance.delete(`/api/v2/oauth2-provider/apps/${id}`); }; export const getOAuth2ProviderAppSecrets = async ( id: string, ): Promise => { - const resp = await coderAxiosInstance.get( + const resp = await axiosInstance.get( `/api/v2/oauth2-provider/apps/${id}/secrets`, ); return resp.data; @@ -1108,7 +1090,7 @@ export const getOAuth2ProviderAppSecrets = async ( export const postOAuth2ProviderAppSecret = async ( id: string, ): Promise => { - const resp = await coderAxiosInstance.post( + const resp = await axiosInstance.post( `/api/v2/oauth2-provider/apps/${id}/secrets`, ); return resp.data; @@ -1118,27 +1100,27 @@ export const deleteOAuth2ProviderAppSecret = async ( appId: string, secretId: string, ): Promise => { - await coderAxiosInstance.delete( + await axiosInstance.delete( `/api/v2/oauth2-provider/apps/${appId}/secrets/${secretId}`, ); }; export const revokeOAuth2ProviderApp = async (appId: string): Promise => { - await coderAxiosInstance.delete(`/oauth2/tokens?client_id=${appId}`); + await axiosInstance.delete(`/oauth2/tokens?client_id=${appId}`); }; export const getAuditLogs = async ( options: TypesGen.AuditLogsRequest, ): Promise => { const url = getURLWithSearchParams("/api/v2/audit", options); - const response = await coderAxiosInstance.get(url); + const response = await axiosInstance.get(url); return response.data; }; export const getTemplateDAUs = async ( templateId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templates/${templateId}/daus`, ); return response.data; @@ -1150,7 +1132,7 @@ export const getDeploymentDAUs = async ( // we truncate the tz offset down to the closest hour. offset = Math.trunc(new Date().getTimezoneOffset() / 60), ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/insights/daus?tz_offset=${offset}`, ); return response.data; @@ -1164,14 +1146,14 @@ export const getTemplateACLAvailable = async ( `/api/v2/templates/${templateId}/acl/available`, options, ); - const response = await coderAxiosInstance.get(url.toString()); + const response = await axiosInstance.get(url.toString()); return response.data; }; export const getTemplateACL = async ( templateId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templates/${templateId}/acl`, ); return response.data; @@ -1181,7 +1163,7 @@ export const updateTemplateACL = async ( templateId: string, data: TypesGen.UpdateTemplateACL, ): Promise<{ message: string }> => { - const response = await coderAxiosInstance.patch( + const response = await axiosInstance.patch( `/api/v2/templates/${templateId}/acl`, data, ); @@ -1190,14 +1172,14 @@ export const updateTemplateACL = async ( export const getApplicationsHost = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/applications/host`); + const response = await axiosInstance.get(`/api/v2/applications/host`); return response.data; }; export const getGroups = async ( organizationId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/groups`, ); return response.data; @@ -1207,7 +1189,7 @@ export const createGroup = async ( organizationId: string, data: TypesGen.CreateGroupRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/organizations/${organizationId}/groups`, data, ); @@ -1215,7 +1197,7 @@ export const createGroup = async ( }; export const getGroup = async (groupId: string): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/groups/${groupId}`); + const response = await axiosInstance.get(`/api/v2/groups/${groupId}`); return response.data; }; @@ -1223,10 +1205,7 @@ export const patchGroup = async ( groupId: string, data: TypesGen.PatchGroupRequest, ): Promise => { - const response = await coderAxiosInstance.patch( - `/api/v2/groups/${groupId}`, - data, - ); + const response = await axiosInstance.patch(`/api/v2/groups/${groupId}`, data); return response.data; }; @@ -1248,13 +1227,13 @@ export const removeMember = async (groupId: string, userId: string) => { }; export const deleteGroup = async (groupId: string): Promise => { - await coderAxiosInstance.delete(`/api/v2/groups/${groupId}`); + await axiosInstance.delete(`/api/v2/groups/${groupId}`); }; export const getWorkspaceQuota = async ( username: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspace-quota/${encodeURIComponent(username)}`, ); return response.data; @@ -1263,7 +1242,7 @@ export const getWorkspaceQuota = async ( export const getAgentListeningPorts = async ( agentID: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspaceagents/${agentID}/listening-ports`, ); return response.data; @@ -1272,7 +1251,7 @@ export const getAgentListeningPorts = async ( export const getWorkspaceAgentSharedPorts = async ( workspaceID: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspaces/${workspaceID}/port-share`, ); return response.data; @@ -1282,7 +1261,7 @@ export const upsertWorkspaceAgentSharedPort = async ( workspaceID: string, req: TypesGen.UpsertWorkspaceAgentPortShareRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( `/api/v2/workspaces/${workspaceID}/port-share`, req, ); @@ -1293,7 +1272,7 @@ export const deleteWorkspaceAgentSharedPort = async ( workspaceID: string, req: TypesGen.DeleteWorkspaceAgentPortShareRequest, ): Promise => { - const response = await coderAxiosInstance.delete( + const response = await axiosInstance.delete( `/api/v2/workspaces/${workspaceID}/port-share`, { data: req, @@ -1305,7 +1284,7 @@ export const deleteWorkspaceAgentSharedPort = async ( // getDeploymentSSHConfig is used by the VSCode-Extension. export const getDeploymentSSHConfig = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/deployment/ssh`); + const response = await axiosInstance.get(`/api/v2/deployment/ssh`); return response.data; }; @@ -1315,23 +1294,23 @@ export type DeploymentConfig = { }; export const getDeploymentConfig = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/deployment/config`); + const response = await axiosInstance.get(`/api/v2/deployment/config`); return response.data; }; export const getDeploymentStats = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/deployment/stats`); + const response = await axiosInstance.get(`/api/v2/deployment/stats`); return response.data; }; export const getReplicas = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/replicas`); + const response = await axiosInstance.get(`/api/v2/replicas`); return response.data; }; export const getFile = async (fileId: string): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/files/${fileId}`, { responseType: "arraybuffer", @@ -1344,7 +1323,7 @@ export const getWorkspaceProxyRegions = async (): Promise< TypesGen.RegionsResponse > => { const response = - await coderAxiosInstance.get>( + await axiosInstance.get>( `/api/v2/regions`, ); return response.data; @@ -1353,7 +1332,7 @@ export const getWorkspaceProxyRegions = async (): Promise< export const getWorkspaceProxies = async (): Promise< TypesGen.RegionsResponse > => { - const response = await coderAxiosInstance.get< + const response = await axiosInstance.get< TypesGen.RegionsResponse >(`/api/v2/workspaceproxies`); return response.data; @@ -1362,13 +1341,13 @@ export const getWorkspaceProxies = async (): Promise< export const createWorkspaceProxy = async ( b: TypesGen.CreateWorkspaceProxyRequest, ): Promise => { - const response = await coderAxiosInstance.post(`/api/v2/workspaceproxies`, b); + const response = await axiosInstance.post(`/api/v2/workspaceproxies`, b); return response.data; }; export const getAppearance = async (): Promise => { try { - const response = await coderAxiosInstance.get(`/api/v2/appearance`); + const response = await axiosInstance.get(`/api/v2/appearance`); return response.data || {}; } catch (ex) { if (isAxiosError(ex) && ex.response?.status === 404) { @@ -1387,14 +1366,14 @@ export const getAppearance = async (): Promise => { export const updateAppearance = async ( b: TypesGen.AppearanceConfig, ): Promise => { - const response = await coderAxiosInstance.put(`/api/v2/appearance`, b); + const response = await axiosInstance.put(`/api/v2/appearance`, b); return response.data; }; export const getTemplateExamples = async ( organizationId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/organizations/${organizationId}/templates/examples`, ); return response.data; @@ -1403,7 +1382,7 @@ export const getTemplateExamples = async ( export const uploadFile = async ( file: File, ): Promise => { - const response = await coderAxiosInstance.post("/api/v2/files", file, { + const response = await axiosInstance.post("/api/v2/files", file, { headers: { "Content-Type": "application/x-tar", }, @@ -1414,7 +1393,7 @@ export const uploadFile = async ( export const getTemplateVersionLogs = async ( versionId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/templateversions/${versionId}/logs`, ); return response.data; @@ -1430,9 +1409,9 @@ export const updateWorkspaceVersion = async ( export const getWorkspaceBuildParameters = async ( workspaceBuildId: TypesGen.WorkspaceBuild["id"], ): Promise => { - const response = await coderAxiosInstance.get< - TypesGen.WorkspaceBuildParameter[] - >(`/api/v2/workspacebuilds/${workspaceBuildId}/parameters`); + const response = await axiosInstance.get( + `/api/v2/workspacebuilds/${workspaceBuildId}/parameters`, + ); return response.data; }; type Claims = { @@ -1452,19 +1431,19 @@ export type GetLicensesResponse = Omit & { }; export const getLicenses = async (): Promise => { - const response = await coderAxiosInstance.get(`/api/v2/licenses`); + const response = await axiosInstance.get(`/api/v2/licenses`); return response.data; }; export const createLicense = async ( data: TypesGen.AddLicenseRequest, ): Promise => { - const response = await coderAxiosInstance.post(`/api/v2/licenses`, data); + const response = await axiosInstance.post(`/api/v2/licenses`, data); return response.data; }; export const removeLicense = async (licenseId: number): Promise => { - await coderAxiosInstance.delete(`/api/v2/licenses/${licenseId}`); + await axiosInstance.delete(`/api/v2/licenses/${licenseId}`); }; export class MissingBuildParameters extends Error { @@ -1556,7 +1535,7 @@ export const updateWorkspace = async ( export const getWorkspaceResolveAutostart = async ( workspaceId: string, ): Promise => { - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/workspaces/${workspaceId}/resolve-autostart`, ); return response.data; @@ -1766,7 +1745,7 @@ export const watchBuildLogsByBuildId = ( export const issueReconnectingPTYSignedToken = async ( params: TypesGen.IssueReconnectingPTYSignedTokenRequest, ): Promise => { - const response = await coderAxiosInstance.post( + const response = await axiosInstance.post( "/api/v2/applications/reconnecting-pty-signed-token", params, ); @@ -1795,7 +1774,7 @@ export const getInsightsUserLatency = async ( filters: InsightsParams, ): Promise => { const params = new URLSearchParams(filters); - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/insights/user-latency?${params}`, ); return response.data; @@ -1805,7 +1784,7 @@ export const getInsightsUserActivity = async ( filters: InsightsParams, ): Promise => { const params = new URLSearchParams(filters); - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/insights/user-activity?${params}`, ); return response.data; @@ -1819,7 +1798,7 @@ export const getInsightsTemplate = async ( params: InsightsTemplateParams, ): Promise => { const searchParams = new URLSearchParams(params); - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/insights/templates?${searchParams}`, ); return response.data; @@ -1827,7 +1806,7 @@ export const getInsightsTemplate = async ( export const getHealth = async (force: boolean = false) => { const params = new URLSearchParams({ force: force.toString() }); - const response = await coderAxiosInstance.get( + const response = await axiosInstance.get( `/api/v2/debug/health?${params}`, ); return response.data; @@ -1835,7 +1814,7 @@ export const getHealth = async (force: boolean = false) => { export const getHealthSettings = async () => { return ( - await coderAxiosInstance.get( + await axiosInstance.get( `/api/v2/debug/health/settings`, ) ).data; @@ -1844,7 +1823,7 @@ export const getHealthSettings = async () => { export const updateHealthSettings = async ( data: TypesGen.UpdateHealthSettings, ) => { - const response = await coderAxiosInstance.put( + const response = await axiosInstance.put( `/api/v2/debug/health/settings`, data, ); @@ -1852,11 +1831,11 @@ export const updateHealthSettings = async ( }; export const putFavoriteWorkspace = async (workspaceID: string) => { - await coderAxiosInstance.put(`/api/v2/workspaces/${workspaceID}/favorite`); + await axiosInstance.put(`/api/v2/workspaces/${workspaceID}/favorite`); }; export const deleteFavoriteWorkspace = async (workspaceID: string) => { - await coderAxiosInstance.delete(`/api/v2/workspaces/${workspaceID}/favorite`); + await axiosInstance.delete(`/api/v2/workspaces/${workspaceID}/favorite`); }; export type GetJFrogXRayScanParams = { @@ -1871,7 +1850,7 @@ export const getJFrogXRayScan = async (options: GetJFrogXRayScanParams) => { }); try { - const res = await coderAxiosInstance.get( + const res = await axiosInstance.get( `/api/v2/integrations/jfrog/xray-scan?${searchParams}`, ); return res.data; diff --git a/site/src/contexts/auth/RequireAuth.tsx b/site/src/contexts/auth/RequireAuth.tsx index 72114ecd51437..d8db9071cc940 100644 --- a/site/src/contexts/auth/RequireAuth.tsx +++ b/site/src/contexts/auth/RequireAuth.tsx @@ -1,6 +1,6 @@ import { type FC, useEffect } from "react"; import { Outlet, Navigate, useLocation } from "react-router-dom"; -import { coderAxiosInstance } from "api/api"; +import { axiosInstance } from "api/api"; import { isApiError } from "api/errors"; import { Loader } from "components/Loader/Loader"; import { ProxyProvider } from "contexts/ProxyContext"; @@ -22,7 +22,7 @@ export const RequireAuth: FC = () => { return; } - const interceptorHandle = coderAxiosInstance.interceptors.response.use( + const interceptorHandle = axiosInstance.interceptors.response.use( (okResponse) => okResponse, (error: unknown) => { // 401 Unauthorized @@ -39,7 +39,7 @@ export const RequireAuth: FC = () => { ); return () => { - coderAxiosInstance.interceptors.response.eject(interceptorHandle); + axiosInstance.interceptors.response.eject(interceptorHandle); }; }, [isLoading, isSigningOut, isSignedIn, signOut]); diff --git a/site/src/contexts/useProxyLatency.ts b/site/src/contexts/useProxyLatency.ts index f474c997ff0c3..497cd457ede51 100644 --- a/site/src/contexts/useProxyLatency.ts +++ b/site/src/contexts/useProxyLatency.ts @@ -1,6 +1,6 @@ import PerformanceObserver from "@fastly/performance-observer-polyfill"; import { useEffect, useReducer, useState } from "react"; -import { coderAxiosInstance } from "api/api"; +import { axiosInstance } from "api/api"; import type { Region } from "api/typesGenerated"; import { generateRandomString } from "utils/random"; @@ -198,7 +198,7 @@ export const useProxyLatency = ( observer.observe({ entryTypes: ["resource"] }); const proxyRequests = Object.keys(proxyChecks).map((latencyURL) => { - return coderAxiosInstance.get(latencyURL, { + return axiosInstance.get(latencyURL, { withCredentials: false, // Must add a custom header to make the request not a "simple request". // We want to force a preflight request. From 353bb7b6082b7833850f5fb4f08949939b05d09b Mon Sep 17 00:00:00 2001 From: Parkreiner Date: Wed, 24 Apr 2024 16:55:51 +0000 Subject: [PATCH 7/7] docs: update variable reference in FE contributing docs --- docs/contributing/frontend.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/frontend.md b/docs/contributing/frontend.md index e24fadf8f53f5..2644c221936ac 100644 --- a/docs/contributing/frontend.md +++ b/docs/contributing/frontend.md @@ -152,7 +152,7 @@ example below: export const getAgentListeningPorts = async ( agentID: string, ): Promise => { - const response = await axios.get( + const response = await axiosInstance.get( `/api/v2/workspaceagents/${agentID}/listening-ports`, ); return response.data;