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: Metabase module controller and service #4072

Merged
merged 26 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
71fb982
feat: new createCollection metabase api call
zz-hh-aa Dec 11, 2024
530f60e
feat: new get collection from metabase function
zz-hh-aa Dec 11, 2024
50f0c18
feat: createCollectionIfDoesNotExist function
zz-hh-aa Dec 11, 2024
6c34c73
feat: new types for collection service
zz-hh-aa Dec 11, 2024
28b3de6
fix: import in metabase client
zz-hh-aa Dec 11, 2024
07a969c
feat: new collection route in api
zz-hh-aa Dec 11, 2024
521689b
fix: controller type error
zz-hh-aa Dec 11, 2024
b097861
test: test for full metabase collection service
zz-hh-aa Dec 11, 2024
30cfbb4
chore: remove unnecessary client import
zz-hh-aa Dec 16, 2024
6f251b1
test: remove unused axios spy
zz-hh-aa Dec 16, 2024
398d9b8
chore: change functions to camelCase
zz-hh-aa Dec 19, 2024
08d38f2
chore: tidy types
zz-hh-aa Dec 19, 2024
632834e
feat: update function name for clarity
zz-hh-aa Dec 19, 2024
15ad49c
fix: update name to slug
zz-hh-aa Dec 19, 2024
8f12f20
chore: replace metabase client w singleton instance
zz-hh-aa Dec 19, 2024
85d73f4
feat: update route and swagger docs
zz-hh-aa Dec 19, 2024
445a576
feat: use team name for metabase collection name
zz-hh-aa Dec 19, 2024
f4dea96
feat: change route to include team slug
zz-hh-aa Dec 19, 2024
5d8818c
chore: remove console.logs
zz-hh-aa Dec 19, 2024
55d089b
test(api): Set up mock for metabase client
DafyddLlyr Dec 20, 2024
c9e9740
chore: remove metabase tag from swagger docs
zz-hh-aa Dec 23, 2024
6d8cd9c
chore: tidy imports and variables
zz-hh-aa Dec 23, 2024
d472c6a
fix: lint issues in analytics yaml
zz-hh-aa Jan 13, 2025
16b1728
nit: tidy comments
zz-hh-aa Jan 20, 2025
b2d7fe5
feat: move ApiResponse type to shared
zz-hh-aa Jan 20, 2025
e86955c
nit: fix comment and validation
zz-hh-aa Jan 28, 2025
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
186 changes: 186 additions & 0 deletions api.planx.uk/modules/analytics/metabase/collection/collection.test.ts
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,6 +1,136 @@
import { createCollectionIfDoesNotExist } from "./service.js";
import { getCollection } from "./getCollection.js";
import nock from "nock";
import { MetabaseError } from "../shared/client.js";
import { $api } from "../../../../client/index.js";
import { updateMetabaseId } from "./updateMetabaseId.js";
import { getTeamIdAndMetabaseId } from "./getTeamIdAndMetabaseId.js";
import { createCollection } from "./createCollection.js";

describe("createCollectionIfDoesNotExist", () => {
beforeEach(() => {
nock.cleanAll();
});

test("creates new collection when metabase ID doesn't exist", async () => {
// Mock getTeamIdAndMetabaseId response with null metabase_id
vi.spyOn($api.client, "request").mockResolvedValueOnce({
teams: [
{
id: 26,
name: "Barnet",
metabase_id: null,
},
],
});

// Mock Metabase API calls
const metabaseMock = nock(process.env.METABASE_URL_EXT!)
.post("/api/collection/", {
name: "Barnet",
})
.reply(200, {
id: 123,
name: "Barnet",
});

const collectionId = await createCollection({
name: "Barnet",
});

expect(collectionId).toBe(123);
expect(metabaseMock.isDone()).toBe(true);
});

test("successfully places new collection in parent", async () => {
// Mock updateMetabaseId response
vi.spyOn($api.client, "request").mockResolvedValueOnce({
update_teams: {
returning: [
{
id: 26,
name: "Barnet",
metabase_id: 123,
},
],
},
});

const testName = "Example council";
const metabaseMock = nock(process.env.METABASE_URL_EXT!);

// Mock collection creation endpoint
metabaseMock
.post("/api/collection/", {
name: testName,
parent_id: 100,
})
.reply(200, {
id: 123,
name: testName,
parent_id: 100,
});

// Mock GET request for verifying the new collection
metabaseMock.get("/api/collection/123").reply(200, {
id: 123,
name: testName,
parent_id: 100,
});

const collectionId = await createCollection({
name: testName,
parentId: 100,
});

// Check the ID is returned correctly
expect(collectionId).toBe(123);

// Verify the collection details using the service function
const collection = await getCollection(collectionId);
expect(collection.parent_id).toBe(100);
expect(metabaseMock.isDone()).toBe(true);
});

test("returns collection correctly no matter collection name case", async () => {
vi.spyOn($api.client, "request").mockResolvedValueOnce({
teams: [
{
id: 26,
name: "barnet",
metabaseId: 20,
},
],
});

const collection = await getTeamIdAndMetabaseId("BARNET");
expect(collection.metabaseId).toBe(20);
});

test("throws error if network failure", async () => {
nock(process.env.METABASE_URL_EXT!)
.get("/api/collection/")
.replyWithError("Network error occurred");

await expect(
createCollection({
name: "Test Collection",
}),
).rejects.toThrow("Network error occurred");
});

test("throws error if API error", async () => {
nock(process.env.METABASE_URL_EXT!).get("/api/collection/").reply(400, {
message: "Bad request",
});

await expect(
createCollection({
name: "Test Collection",
}),
).rejects.toThrow(MetabaseError);
});
});

describe("getTeamIdAndMetabaseId", () => {
beforeEach(() => {
Expand Down Expand Up @@ -90,3 +220,59 @@ describe("updateMetabaseId", () => {
await expect(updateMetabaseId(1, 123)).rejects.toThrow("GraphQL error");
});
});

describe("edge cases", () => {
beforeEach(() => {
nock.cleanAll();
vi.clearAllMocks();
vi.resetAllMocks();
});

test("handles missing name", async () => {
await expect(
createCollectionIfDoesNotExist({
name: "",
}),
).rejects.toThrow();
});

test("handles names with special characters", async () => {
const specialName = "@#$%^&*";

nock(process.env.METABASE_URL_EXT!).get("/api/collection/").reply(200, []);

nock(process.env.METABASE_URL_EXT!)
.post("/api/collection/", {
name: specialName,
})
.reply(200, {
id: 789,
name: specialName,
});

const collection = await createCollection({
name: specialName,
});
expect(collection).toBe(789);
});

test("handles very long names", async () => {
const longName = "A".repeat(101);

nock(process.env.METABASE_URL_EXT!).get("/api/collection/").reply(200, []);

nock(process.env.METABASE_URL_EXT!)
.post("/api/collection/", {
name: longName,
})
.reply(400, {
message: "Name too long",
});

await expect(
createCollectionIfDoesNotExist({
name: longName,
}),
).rejects.toThrow();
});
});
18 changes: 18 additions & 0 deletions api.planx.uk/modules/analytics/metabase/collection/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createCollectionIfDoesNotExist } from "./service.js";
import type { NewCollectionRequestHandler } from "./types.js";

export const MetabaseCollectionsController: NewCollectionRequestHandler =
async (_req, res) => {
try {
const params = res.locals.parsedReq.body;
const collection = await createCollectionIfDoesNotExist(params);
res.status(201).json({ data: collection });
} catch (error) {
res.status(400).json({
error:
error instanceof Error
? error.message
: "An unexpected error occurred",
});
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { createMetabaseClient } from "../shared/client.js";
import type { NewCollectionParams } from "./types.js";

const client = createMetabaseClient();

export async function createCollection(
params: NewCollectionParams,
): Promise<any> {

Check warning on line 8 in api.planx.uk/modules/analytics/metabase/collection/createCollection.ts

View workflow job for this annotation

GitHub Actions / Run API Tests

Unexpected any. Specify a different type
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
const transformedParams = {
name: params.name,
parent_id: params.parentId,
};

const response = await client.post(`/api/collection/`, transformedParams);

console.log(
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
`New collection: ${response.data.name}, new collection ID: ${response.data.id}`,
);
return response.data.id;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createMetabaseClient } from "../shared/client.js";
import type { GetCollectionResponse } from "./types.js";

const client = createMetabaseClient();
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
/**
* Retrieves info on a collection from Metabase, use to check a parent. Currently only used in tests but could be useful for other Metabase functionality
* @param id
* @returns
*/
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
export async function getCollection(
id: number,
): Promise<GetCollectionResponse> {
const response = await client.get(`/api/collection/${id}`);
return response.data;
}
33 changes: 33 additions & 0 deletions api.planx.uk/modules/analytics/metabase/collection/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { updateMetabaseId } from "./updateMetabaseId.js";
import type { NewCollectionParams } from "./types.js";
import { getTeamIdAndMetabaseId } from "./getTeamIdAndMetabaseId.js";
import { createCollection } from "./createCollection.js";

/**
* First uses name to get teams.id and .metabase_id, if present.
* If metabase_id is null, return an object that includes its id. If not, create the collection.
* @params `name` is required, but `description` and `parent_id` are optional.
* @returns `response.data`, so use dot notation to access `id` or `parent_id`.
*/
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
export async function createCollectionIfDoesNotExist(
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
params: NewCollectionParams,
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
): Promise<number> {
try {
const { metabaseId, id: teamId } = await getTeamIdAndMetabaseId(
params.name,
);

if (metabaseId) {
return metabaseId;
}

// Create new Metabase collection if !metabaseId
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
const newMetabaseId = await createCollection(params);
await updateMetabaseId(teamId, newMetabaseId);
console.log({ newMetabaseId });
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
return newMetabaseId;
} catch (error) {
console.error("Error in createCollectionIfDoesNotExist:", error);
throw error;
}
}
55 changes: 55 additions & 0 deletions api.planx.uk/modules/analytics/metabase/collection/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { z } from "zod";
import type { ValidatedRequestHandler } from "../../../../shared/middleware/validate.js";

type ApiResponse<T> = {
data?: T;
error?: string;
};

/** Interface for incoming request, in camelCase */
export interface NewCollectionParams {
name: string;
description?: string;
/** Optional; if the collection is a child of a parent, specify parent ID here */
parentId?: number;
}

/** Interface for request after transforming to snake case (Metabase takes snake while PlanX API takes camel) */
export interface MetabaseCollectionParams {
name: string;
description?: string;
parent_id?: number;
}

/** Metbase collection ID for the the "Council" collection **/
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
// const COUNCILS_COLLECTION_ID = 58;
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved

export const createCollectionIfDoesNotExistSchema = z.object({
body: z
.object({
name: z.string(),
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
description: z.string().optional(),
parentId: z.number().optional(), //.default(COUNCILS_COLLECTION_ID),
})
.transform((data) => ({
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
name: data.name,
description: data.description,
parent_id: data.parentId,
})),
});

export type NewCollectionRequestHandler = ValidatedRequestHandler<
typeof createCollectionIfDoesNotExistSchema,
ApiResponse<number>
>;

export interface NewCollectionResponse {
id: number;
name: string;
}

export interface GetCollectionResponse {
id: number;
name: string;
parent_id: number;
}
3 changes: 0 additions & 3 deletions api.planx.uk/modules/analytics/metabase/shared/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import axios from "axios";
import {
validateConfig,
createMetabaseClient,
MetabaseError,
} from "./client.js";
import nock from "nock";

const axiosCreateSpy = vi.spyOn(axios, "create");

describe("Metabase client", () => {
beforeEach(() => {
vi.clearAllMocks();
Expand Down
1 change: 1 addition & 0 deletions api.planx.uk/modules/analytics/metabase/shared/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import axios from "axios";
import assert from "assert";
import type {
AxiosInstance,
AxiosError,
Expand Down Expand Up @@ -52,7 +53,7 @@
export const createMetabaseClient = (): AxiosInstance => {
const config = validateConfig();

const client = axios.create({

Check failure on line 56 in api.planx.uk/modules/analytics/metabase/shared/client.ts

View workflow job for this annotation

GitHub Actions / Run API Tests

modules/send/s3/index.test.ts

TypeError: default.create is not a function ❯ Module.createMetabaseClient modules/analytics/metabase/shared/client.ts:56:24 ❯ modules/analytics/metabase/collection/createCollection.ts:4:16 ❯ modules/analytics/metabase/collection/service.ts:3:31
baseURL: config.baseURL,
headers: {
"X-API-Key": config.apiKey,
Expand Down
7 changes: 7 additions & 0 deletions api.planx.uk/modules/analytics/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
logUserExitController,
logUserResumeController,
} from "./analyticsLog/controller.js";
import { MetabaseCollectionsController } from "./metabase/collection/controller.js";
import { createCollectionIfDoesNotExistSchema } from "./metabase/collection/types.js";

const router = Router();

Expand All @@ -18,5 +20,10 @@ router.post(
validate(logAnalyticsSchema),
logUserResumeController,
);
router.post(
"/collection",
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
validate(createCollectionIfDoesNotExistSchema),
MetabaseCollectionsController,
zz-hh-aa marked this conversation as resolved.
Show resolved Hide resolved
);

export default router;
Loading