Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: migrate from axios to fetch with Codemod2.0 #989

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/auth-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"@fastify/busboy": "^2.1.1",
"@fastify/cors": "8.5.0",
"@fastify/rate-limit": "9.0.1",
"axios": "^1.6.8",
"dotenv": "^16.4.5",
"fastify": "4.25.1",
"valibot": "^0.24.1"
Expand Down
1 change: 0 additions & 1 deletion apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
"@fastify/rate-limit": "9.0.1",
"@types/tar": "^6.1.11",
"ai": "2.2.29",
"axios": "^1.6.8",
"bullmq": "^5.7.5",
"chatgpt": "5.2.5",
"chromadb": "1.7.2",
Expand Down
48 changes: 26 additions & 22 deletions apps/backend/src/plugins/authPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { OrganizationMembership, User } from "@codemod-com/utilities";
import axios from "axios";
import {
type OrganizationMembership,
type User,
extendedFetch,
} from "@codemod-com/utilities";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import { environment } from "../util";
Expand Down Expand Up @@ -38,12 +41,13 @@ async function authPlugin(fastify: FastifyInstance, _opts: unknown) {
try {
const authHeader = request.headers.authorization;

if (!authHeader) reply.code(401).send({ error: "Unauthorized" });
if (!authHeader) {
reply.code(401).send({ error: "Unauthorized" });
return;
}

await axios.get(`${environment.AUTH_SERVICE_URL}/verifyToken`, {
headers: {
Authorization: authHeader,
},
await extendedFetch(`${environment.AUTH_SERVICE_URL}/verifyToken`, {
headers: { Authorization: authHeader },
});
} catch (error) {
console.error(error);
Expand Down Expand Up @@ -72,16 +76,17 @@ async function authPlugin(fastify: FastifyInstance, _opts: unknown) {
return;
}

const { data } = await axios.get(
const response = await extendedFetch(
`${environment.AUTH_SERVICE_URL}/userData`,
{
headers: {
Authorization: authHeader,
},
},
{ headers: { Authorization: authHeader } },
);

const { user, organizations, allowedNamespaces } = data;
const { user, organizations, allowedNamespaces } =
(await response.json()) as {
user?: User;
organizations?: OrganizationMembership[];
allowedNamespaces?: string[];
};

request.user = user;
request.organizations = organizations;
Expand All @@ -104,18 +109,17 @@ async function authPlugin(fastify: FastifyInstance, _opts: unknown) {
try {
const authHeader = request.headers.authorization;

if (!authHeader) reply.code(401).send({ error: "Unauthorized" });
if (!authHeader) {
reply.code(401).send({ error: "Unauthorized" });
return;
}

const { data } = await axios.get(
const response = await extendedFetch(
`${environment.AUTH_SERVICE_URL}/oAuthToken`,
{
headers: {
Authorization: authHeader,
},
},
{ headers: { Authorization: authHeader } },
);

const { token } = data;
const { token } = (await response.json()) as { token?: string };

request.token = token;
} catch {
Expand Down
78 changes: 46 additions & 32 deletions apps/backend/src/publishHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,16 @@ const mocks = vi.hoisted(() => {
findUnique: vi.fn(),
},
},
axios: {
get: vi.fn().mockImplementation((url: string, ...args: unknown[]) => ({
data: GET_USER_RETURN,
})),
post: vi.fn().mockImplementation(() => ({})),
},
fetch: vi.fn().mockImplementation((url, options) => {
if (options.method === "GET" || !options.method) {
return Promise.resolve({
json: () => Promise.resolve(GET_USER_RETURN),
ok: true,
});
}

return Promise.resolve({ json: () => GET_USER_RETURN, ok: true });
}),
S3Client,
TarService,
PutObjectCommand,
Expand All @@ -62,10 +66,6 @@ vi.mock("@codemod-com/database", async () => {
return { ...actual, prisma: mocks.prisma };
});

vi.mock("axios", async () => {
return { default: mocks.axios };
});

vi.mock("@aws-sdk/client-s3", async () => {
const actual = await vi.importActual("@aws-sdk/client-s3");

Expand Down Expand Up @@ -116,7 +116,7 @@ vi.mock("@codemod-com/utilities", async () => {
};
});

vi.stubGlobal("fetch", vi.fn());
vi.stubGlobal("fetch", mocks.fetch);

describe("/publish route", async () => {
const fastify = await runServer();
Expand Down Expand Up @@ -218,26 +218,34 @@ describe("/publish route", async () => {
requestTimeout: 5000,
});

expect(mocks.axios.post).toHaveBeenCalledOnce();
expect(mocks.axios.post).toHaveBeenCalledWith(
expect(mocks.fetch).toHaveBeenCalledTimes(3);
expect(mocks.fetch).toHaveBeenNthCalledWith(
2,
"https://hooks.zapier.com/hooks/catch/18983913/2ybuovt/",
{
codemod: {
name: codemodRcContents.name,
from: codemodRcContents.applicability?.from?.map((tuple) =>
tuple.join(" "),
),
to: codemodRcContents.applicability?.to?.map((tuple) =>
tuple.join(" "),
),
engine: codemodRcContents.engine,
publishedAt: MOCK_TIMESTAMP,
},
author: {
username: GET_USER_RETURN.user.username,
name: `${GET_USER_RETURN.user.firstName} ${GET_USER_RETURN.user.lastName}`,
email: GET_USER_RETURN.user.emailAddresses[0]?.emailAddress,
body: JSON.stringify({
codemod: {
name: codemodRcContents.name,
from: codemodRcContents.applicability?.from?.map((tuple) =>
tuple.join(" "),
),
to: codemodRcContents.applicability?.to?.map((tuple) =>
tuple.join(" "),
),
engine: codemodRcContents.engine,
publishedAt: MOCK_TIMESTAMP,
},
author: {
username: GET_USER_RETURN.user.username,
name: `${GET_USER_RETURN.user.firstName} ${GET_USER_RETURN.user.lastName}`,
email: GET_USER_RETURN.user.emailAddresses[0]?.emailAddress,
},
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
signal: expect.any(AbortSignal),
},
);

Expand Down Expand Up @@ -605,8 +613,9 @@ describe("/publish route", async () => {
describe("when publishing via org", async () => {
it("should go through happy path if user has access to the org", async () => {
mocks.prisma.codemodVersion.findFirst.mockImplementation(() => null);
mocks.axios.get.mockImplementation(() => ({
data: { ...GET_USER_RETURN, allowedNamespaces: ["org"] },
mocks.fetch.mockImplementation(() => ({
json: () => ({ ...GET_USER_RETURN, allowedNamespaces: ["org"] }),
ok: true,
}));
mocks.prisma.codemod.upsert.mockImplementation(() => {
return { createdAt: { getTime: () => MOCK_TIMESTAMP }, id: "id" };
Expand Down Expand Up @@ -669,8 +678,13 @@ describe("/publish route", async () => {

it("should fail if user has no access to the org", async () => {
mocks.prisma.codemodVersion.findFirst.mockImplementation(() => null);
mocks.axios.get.mockImplementation(() => ({
data: { ...GET_USER_RETURN, organizations: [], allowedNamespaces: [] },
mocks.fetch.mockImplementation(() => ({
json: () => ({
...GET_USER_RETURN,
organizations: [],
allowedNamespaces: [],
}),
ok: true,
}));

const codemodRcContents: CodemodConfigInput = {
Expand Down
43 changes: 25 additions & 18 deletions apps/backend/src/publishHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import {
TarService,
buildCodemodSlug,
codemodNameRegex,
extendedFetch,
isNeitherNullNorUndefined,
parseCodemodConfig,
} from "@codemod-com/utilities";
import axios from "axios";
import type { RouteHandler } from "fastify";
import * as semver from "semver";
import type { UserDataPopulatedRequest } from "./plugins/authPlugin";
Expand Down Expand Up @@ -350,25 +350,32 @@ export const publishHandler: RouteHandler<{

if (latestVersion === null) {
try {
await axios.post(
await extendedFetch(
"https://hooks.zapier.com/hooks/catch/18983913/2ybuovt/",
{
codemod: {
name,
from: codemodRc.applicability?.from?.map((tuple) =>
tuple.join(" "),
),
to: codemodRc.applicability?.to?.map((tuple) => tuple.join(" ")),
engine: codemodRc.engine,
publishedAt: createdAtTimestamp,
},
author: {
username,
name: `${firstName ?? ""} ${lastName ?? ""}`.trim() || null,
email:
emailAddresses.find((e) => e.id === primaryEmailAddressId)
?.emailAddress ?? null,
},
method: "POST",
body: JSON.stringify({
codemod: {
name,
from: codemodRc.applicability?.from?.map((tuple) =>
tuple.join(" "),
),
to: codemodRc.applicability?.to?.map((tuple) =>
tuple.join(" "),
),
engine: codemodRc.engine,
publishedAt: createdAtTimestamp,
},
author: {
username,
name: `${firstName ?? ""} ${lastName ?? ""}`.trim() || null,
email:
emailAddresses.find((e) => e.id === primaryEmailAddressId)
?.emailAddress ?? null,
},
}),
headers: { "Content-Type": "application/json" },
signal: AbortSignal.timeout(5000),
},
);
} catch (err) {
Expand Down
Loading
Loading