Skip to content

Commit

Permalink
format backend
Browse files Browse the repository at this point in the history
  • Loading branch information
hansaskov committed Dec 25, 2024
1 parent 96b0600 commit 8ba44c7
Show file tree
Hide file tree
Showing 8 changed files with 111 additions and 115 deletions.
16 changes: 7 additions & 9 deletions services/backend/src/auth/login/microsoft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,23 +66,21 @@ export const microsoftRoute = new Elysia()
Authorization: `Bearer ${tokens.accessToken()}`,
},
},
)
.then(r => r.json() as Record<string, any>)
).then((r) => r.json() as Record<string, any>);

console.log(userResponse)
console.log(userResponse);

const parsedUserResponse = convertKeys(userResponse);

console.log(parsedUserResponse)
console.log(parsedUserResponse);

if (!validateUser.Check(parsedUserResponse)) {
const errorMessage = `Server Failed to parse response when getting user info from microsoft. Expected schema: ${UserSchema.description}, Actual schema: ${parsedUserResponse}`
const errorMessage = `Server Failed to parse response when getting user info from microsoft. Expected schema: ${UserSchema.description}, Actual schema: ${parsedUserResponse}`;

console.error(errorMessage)
console.error(errorMessage);
return error(500, errorMessage);
}


const userParsed = validateUser.Decode(parsedUserResponse);

const existingUser = await Queries.users.selectUniqueWithProvider({
Expand Down Expand Up @@ -121,8 +119,8 @@ export const microsoftRoute = new Elysia()
}),
cookie: t.Cookie({
microsoftState: t.String(),
microsoftCode: t.String()
})
microsoftCode: t.String(),
}),
},
);

Expand Down
3 changes: 1 addition & 2 deletions services/backend/src/db/collections/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const Queries = {
organizations: organizationQueries,
usersToOrganizations: usersToOrganizationsQueries,
systems: systemQueries,
part: partQueries
part: partQueries,
};

export const Schema = {
Expand All @@ -111,7 +111,6 @@ export const Schema = {
organizations: selectOrganizationsSchema,
systems: selectSystemsSchema,
part: selectPartsSchema,

},
"select",
),
Expand Down
2 changes: 1 addition & 1 deletion services/backend/src/db/collections/parts/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const partsApi = new Elysia({ prefix: "parts" })
"Only superadmins are allowed to select all parts",
);
}

return await Queries.part.selectAll();
})
.patch(
Expand Down
2 changes: 0 additions & 2 deletions services/backend/src/db/collections/parts/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ export const insertPartsSchema = createInsertSchema(parts, {
name: t.String({ minLength: 1 }),
});



export type Part = typeof parts.$inferSelect;
export type PartNew = typeof parts.$inferInsert;
export type PartUpdate = PartialExcept<Part, "id">;
11 changes: 8 additions & 3 deletions services/backend/src/db/collections/systems/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@ import { t } from "elysia";
import type { PartialExcept } from "../../../types/strict";
import { organizations } from "../organizations/schema";

export const systemModelEnumList = ["VisioPointer",
export const systemModelEnumList = [
"VisioPointer",
"VisioCompact",
"VisioLine",
"SmartInspector",
"360 Inspector",
"VisioOne",
"IML-Inspector"] as const;
"IML-Inspector",
] as const;

export const systemModelEnum = pgEnum("system_models_enum", systemModelEnumList);
export const systemModelEnum = pgEnum(
"system_models_enum",
systemModelEnumList,
);

export const systems = pgTable("systems", {
id: text()
Expand Down
6 changes: 4 additions & 2 deletions services/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { readings } from "./db/collections/readings/api";
import { systemsApi } from "./db/collections/systems/api";
import { partsApi } from "$db/collections/parts/api";


const api = new Elysia({ prefix: "/api" })
.use(authRoutes)
.use(readings)
Expand All @@ -16,7 +15,10 @@ const api = new Elysia({ prefix: "/api" })
.use(partsApi);

const app = new Elysia({ precompile: true })
.get(".well-known/microsoft-identity-association.json", Bun.file('public/.well-known/microsoft-identity-association.json'))
.get(
".well-known/microsoft-identity-association.json",
Bun.file("public/.well-known/microsoft-identity-association.json"),
)
.use(logger())
.use(swagger({ path: "/api/swagger" }))
.use(api)
Expand Down
138 changes: 65 additions & 73 deletions services/backend/src/utils/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,87 +3,79 @@ import { describe, it, expect } from "bun:test";
import { convertKeys } from "./transform";

describe("convertKeys - Edge Cases", () => {
it("should handle empty objects and arrays", () => {
expect(convertKeys({})).toEqual({});
expect(convertKeys([])).toEqual([]);
});
it("should handle empty objects and arrays", () => {
expect(convertKeys({})).toEqual({});
expect(convertKeys([])).toEqual([]);
});

it("should handle mixed nested structures", () => {
const input = {
Complex_Structure: {
Array_Of_Objects: [
{ First_Item: 1 },
{ Second_Item: 2 }
],
Nested_Array: [[{ Deep_Nested: true }]],
Mixed_Values: {
Some_String: "test",
Some_Number: 123,
Some_Boolean: true,
Some_Null: null,
Some_Undefined: undefined
}
}
};
it("should handle mixed nested structures", () => {
const input = {
Complex_Structure: {
Array_Of_Objects: [{ First_Item: 1 }, { Second_Item: 2 }],
Nested_Array: [[{ Deep_Nested: true }]],
Mixed_Values: {
Some_String: "test",
Some_Number: 123,
Some_Boolean: true,
Some_Null: null,
Some_Undefined: undefined,
},
},
};

const expected = {
complexstructure: {
arrayofobjects: [
{ firstitem: 1 },
{ seconditem: 2 }
],
nestedarray: [[{ deepnested: true }]],
mixedvalues: {
somestring: "test",
somenumber: 123,
someboolean: true,
somenull: null,
someundefined: undefined
}
}
};

expect(convertKeys(input)).toEqual(expected);
});
})
const expected = {
complexstructure: {
arrayofobjects: [{ firstitem: 1 }, { seconditem: 2 }],
nestedarray: [[{ deepnested: true }]],
mixedvalues: {
somestring: "test",
somenumber: 123,
someboolean: true,
somenull: null,
someundefined: undefined,
},
},
};

expect(convertKeys(input)).toEqual(expected);
});
});

describe("convertKeys - Microsoft Graph User Data", () => {
it("should correctly transform Microsoft Graph user data structure", () => {
const input = {
sub: "b-PncAH_Eo20KlWh1NeP0y8T0gmrcexwXB5RC_5WxAI",
name: "Tanita Hjort Sode",
family_name: "Sode",
given_name: "Tanita Hjort",
picture: "https://graph.microsoft.com/v1.0/me/photo/$value",
email: "[email protected]"
};
it("should correctly transform Microsoft Graph user data structure", () => {
const input = {
sub: "b-PncAH_Eo20KlWh1NeP0y8T0gmrcexwXB5RC_5WxAI",
name: "Tanita Hjort Sode",
family_name: "Sode",
given_name: "Tanita Hjort",
picture: "https://graph.microsoft.com/v1.0/me/photo/$value",
email: "[email protected]",
};

const expected = {
sub: "b-PncAH_Eo20KlWh1NeP0y8T0gmrcexwXB5RC_5WxAI",
name: "Tanita Hjort Sode",
familyname: "Sode",
givenname: "Tanita Hjort",
picture: "https://graph.microsoft.com/v1.0/me/photo/$value",
email: "[email protected]"
};
const expected = {
sub: "b-PncAH_Eo20KlWh1NeP0y8T0gmrcexwXB5RC_5WxAI",
name: "Tanita Hjort Sode",
familyname: "Sode",
givenname: "Tanita Hjort",
picture: "https://graph.microsoft.com/v1.0/me/photo/$value",
email: "[email protected]",
};

const result = convertKeys(input);
expect(result).toEqual(expected);
});
const result = convertKeys(input);
expect(result).toEqual(expected);
});

// Additional test to verify specific field transformations
it("should specifically verify each field transformation", () => {
const input = {
family_name: "Sode",
given_name: "Tanita Hjort"
};
// Additional test to verify specific field transformations
it("should specifically verify each field transformation", () => {
const input = {
family_name: "Sode",
given_name: "Tanita Hjort",
};

const result = convertKeys(input);
const result = convertKeys(input);

// Individual field checks
expect(result).toHaveProperty('familyname');
expect(result).toHaveProperty('givenname');
});
// Individual field checks
expect(result).toHaveProperty("familyname");
expect(result).toHaveProperty("givenname");
});
});

48 changes: 25 additions & 23 deletions services/backend/src/utils/transform.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
// Custom type to remove underscores and convert to lowercase
type RemoveUnderscoreAndLowercase<S extends string> =
S extends `${infer F}_${infer R}`
? `${Lowercase<F>}${RemoveUnderscoreAndLowercase<R>}`
: Lowercase<S>;
type RemoveUnderscoreAndLowercase<S extends string> =
S extends `${infer F}_${infer R}`
? `${Lowercase<F>}${RemoveUnderscoreAndLowercase<R>}`
: Lowercase<S>;

// Modified TransformKeys type using the custom type
type TransformKeys<T> = T extends Array<any>
? Array<TransformKeys<T[number]>>
: T extends object
? { [K in keyof T as RemoveUnderscoreAndLowercase<string & K>]: TransformKeys<T[K]> }
: T;
? Array<TransformKeys<T[number]>>
: T extends object
? {
[K in keyof T as RemoveUnderscoreAndLowercase<
string & K
>]: TransformKeys<T[K]>;
}
: T;

export function convertKeys<T extends Record<string, any>>(
obj: T
obj: T,
): TransformKeys<T> {
if (obj === null || typeof obj !== 'object') {
return obj as TransformKeys<T>;
}
if (obj === null || typeof obj !== "object") {
return obj as TransformKeys<T>;
}

if (Array.isArray(obj)) {
return obj.map(item => convertKeys(item)) as TransformKeys<T>;
}
if (Array.isArray(obj)) {
return obj.map((item) => convertKeys(item)) as TransformKeys<T>;
}

return Object.entries(obj).reduce((acc: any, [key, value]) => {
const newKey = key.toLowerCase().replace(/_/g, '');
acc[newKey] = typeof value === 'object'
? convertKeys(value)
: value;
return acc;
}, {}) as TransformKeys<T>;
}
return Object.entries(obj).reduce((acc: any, [key, value]) => {
const newKey = key.toLowerCase().replace(/_/g, "");
acc[newKey] = typeof value === "object" ? convertKeys(value) : value;
return acc;
}, {}) as TransformKeys<T>;
}

0 comments on commit 8ba44c7

Please sign in to comment.