Skip to content

Commit

Permalink
Refactor tsAlias.types.ts and tables.types.ts to improve type definit…
Browse files Browse the repository at this point in the history
…ions and simplify table selection
  • Loading branch information
Adammatthiesen committed Dec 10, 2024
1 parent 042a9fb commit 20ece6d
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 48 deletions.
2 changes: 0 additions & 2 deletions packages/studiocms_core/src/db/tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ export const StudioCMSPageData = defineTable({
default:
'https://images.unsplash.com/photo-1707343843982-f8275f3994c5?q=80&w=1032&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D',
}),
// TODO: Remove typo column name once new onboarding page is ready to use
catagories: column.json({ default: [], optional: true }),
categories: column.json({ default: [], optional: true }),
tags: column.json({ default: [], optional: true }),
authorId: column.text({ optional: true }),
Expand Down
34 changes: 20 additions & 14 deletions packages/studiocms_core/src/sdk-utils/get/getPermissionLists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ import { combineRanks, verifyRank } from '../utils';
export async function getPermissionsLists(list: AvailableLists): Promise<PermissionsList[]> {
switch (list) {
case 'all': {
const currentPermittedUsers = await db.select().from(tsPermissions);
const existingUsers = await db.select().from(tsUsers);
const [currentPermittedUsers, existingUsers] = await db.batch([
db.select().from(tsPermissions),
db.select().from(tsUsers),
]);

const owners = verifyRank(existingUsers, currentPermittedUsers, 'owner');

Expand All @@ -49,27 +51,31 @@ export async function getPermissionsLists(list: AvailableLists): Promise<Permiss
];
}
case 'owners': {
const currentPermittedUsers = await db.select().from(tsPermissions);
const existingUsers = await db.select().from(tsUsers);

const [currentPermittedUsers, existingUsers] = await db.batch([
db.select().from(tsPermissions),
db.select().from(tsUsers),
]);
return verifyRank(existingUsers, currentPermittedUsers, 'owner');
}
case 'admins': {
const currentPermittedUsers = await db.select().from(tsPermissions);
const existingUsers = await db.select().from(tsUsers);

const [currentPermittedUsers, existingUsers] = await db.batch([
db.select().from(tsPermissions),
db.select().from(tsUsers),
]);
return verifyRank(existingUsers, currentPermittedUsers, 'admin');
}
case 'editors': {
const currentPermittedUsers = await db.select().from(tsPermissions);
const existingUsers = await db.select().from(tsUsers);

const [currentPermittedUsers, existingUsers] = await db.batch([
db.select().from(tsPermissions),
db.select().from(tsUsers),
]);
return verifyRank(existingUsers, currentPermittedUsers, 'editor');
}
case 'visitors': {
const currentPermittedUsers = await db.select().from(tsPermissions);
const existingUsers = await db.select().from(tsUsers);

const [currentPermittedUsers, existingUsers] = await db.batch([
db.select().from(tsPermissions),
db.select().from(tsUsers),
]);
return verifyRank(existingUsers, currentPermittedUsers, 'visitor');
}
default:
Expand Down
21 changes: 21 additions & 0 deletions packages/studiocms_core/src/sdk-utils/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Table } from '@astrojs/db/runtime';
import type {
AvailableLists,
CombinedRank,
Expand Down Expand Up @@ -64,6 +65,26 @@ export type {
tsUsersSelect,
};

export type GenericTable = Table<
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
any,
{
id: {
type: 'text' | 'number';
schema: {
unique: false;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
deprecated: any;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
name: any;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
collection: any;
primaryKey: true;
};
};
}
>;

/**
* Represents the structure for adding a database entry for a page.
*
Expand Down
5 changes: 1 addition & 4 deletions packages/studiocms_core/src/sdk-utils/types/tables.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ export type SiteConfig = Omit<tsSiteConfigSelect, 'id'>;
* Represents a stripped-down version of the `tsPageDataSelect` type,
* excluding the properties 'catagories', 'categories', 'tags', and 'contributorIds'.
*/
export type PageDataStripped = Omit<
tsPageDataSelect,
'catagories' | 'categories' | 'tags' | 'contributorIds'
>;
export type PageDataStripped = Omit<tsPageDataSelect, 'categories' | 'tags' | 'contributorIds'>;

/**
* Represents a type that picks the 'id' property from the tsPageContentSelect type.
Expand Down
64 changes: 36 additions & 28 deletions packages/studiocms_core/src/sdk-utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
CombinedPageData,
CombinedRank,
CombinedUserData,
GenericTable,
SingleRank,
tsPageDataCategoriesSelect,
tsPageDataSelect,
Expand Down Expand Up @@ -39,6 +40,35 @@ export async function collectUserData(user: tsUsersSelect): Promise<CombinedUser
};
}

/**
* Executes a batch query on the database for the given IDs and table.
*
* @template returnType - The type of the return value.
* @param {Array<number | string>} ids - An array of IDs to query.
* @param {GenericTable} table - The table to query against.
* @returns {Promise<returnType[]>} A promise that resolves to an array of results of type `returnType`.
*/
export async function runDbBatchQuery<returnType>(
ids: Array<number | string>,
table: GenericTable
): Promise<returnType[]> {
const batchQueries = [];

for (const id of ids) {
batchQueries.push(db.select().from(table).where(eq(table.id, id)));
}

const [head, ...tail] = batchQueries;

if (head) {
const queryResults = await db.batch([head, ...tail]);
// Flatten and filter the results
return queryResults.flat().filter(Boolean) as returnType[];
}

return [] as returnType[];
}

/**
* Collects and combines page data including categories, tags, contributors, and multilingual content.
*
Expand All @@ -54,36 +84,14 @@ export async function collectUserData(user: tsUsersSelect): Promise<CombinedUser
* 6. Returns the combined page data including categories, tags, contributors, multilingual content, and default content.
*/
export async function collectPageData(page: tsPageDataSelect): Promise<CombinedPageData> {
const categories: tsPageDataCategoriesSelect[] = [];
const tags: tsPageDataTagsSelect[] = [];
const contributors: string[] = [];

const [allCategories, allTags, allUsers] = await db.batch([
db.select().from(tsPageDataCategories),
db.select().from(tsPageDataTags),
db.select().from(tsUsers),
]);
const categories = await runDbBatchQuery<tsPageDataCategoriesSelect>(
page.categories as number[],
tsPageDataCategories
);

for (const category of page.categories as number[]) {
const categoryData = allCategories.find((cat) => cat.id === category);
if (categoryData) {
categories.push(categoryData);
}
}
const tags = await runDbBatchQuery<tsPageDataTagsSelect>(page.tags as number[], tsPageDataTags);

for (const tag of page.tags as number[]) {
const tagData = allTags.find((t) => t.id === tag);
if (tagData) {
tags.push(tagData);
}
}

for (const contributor of page.contributorIds as string[]) {
const contributorData = allUsers.find((user) => user.id === contributor);
if (contributorData) {
contributors.push(contributorData.id);
}
}
const contributors = await runDbBatchQuery<string>(page.contributorIds as string[], tsUsers);

const multiLangContentData = await db
.select()
Expand Down

0 comments on commit 20ece6d

Please sign in to comment.