Skip to content

Commit

Permalink
modules and some others
Browse files Browse the repository at this point in the history
  • Loading branch information
pinocchio-life-like committed Dec 28, 2024
1 parent 65f1b6f commit 74a5dd7
Show file tree
Hide file tree
Showing 12 changed files with 103 additions and 74 deletions.
19 changes: 13 additions & 6 deletions server/src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
import { createInsertSchema, createSelectSchema } from 'drizzle-zod';
import { createId } from '@paralleldrive/cuid2';

interface OfflineMap {
export interface OfflineMapMetadata {
name: string;
styleURL: string;
bounds: [number[], number[]];
Expand Down Expand Up @@ -43,7 +43,7 @@ export const user = sqliteTable('user', {
mode: 'timestamp',
}),
offlineMaps: text('offline_maps', { mode: 'json' }).$type<
Record<string, OfflineMap>
Record<string, OfflineMapMetadata>
>(),
role: text('role', { enum: ['admin', 'user'] })
.default('user')
Expand Down Expand Up @@ -145,7 +145,7 @@ export const pack = sqliteTable('pack', {
// pkWithCustomName: primaryKey({
// name: 'id',
// columns: [table.packId, table.ownerId],
// }),
// }),
// };
// },
// );
Expand Down Expand Up @@ -279,11 +279,13 @@ export const offlineMap = sqliteTable(
.primaryKey()
.$defaultFn(() => createId()),
name: text('name').notNull(),
bounds: text('bounds', { mode: 'json' }).$type<OfflineMap['bounds']>(),
bounds: text('bounds', { mode: 'json' }).$type<
OfflineMapMetadata['bounds']
>(),
minZoom: integer('minZoom').notNull(),
maxZoom: integer('maxZoom').notNull(),
metadata: text('metadata', { mode: 'json' }).$type<
OfflineMap['metadata']
OfflineMapMetadata['metadata']
>(),
owner_id: text('owner_id').references(() => user.id, {
onDelete: 'cascade',
Expand Down Expand Up @@ -422,7 +424,9 @@ export const trip = sqliteTable('trip', {
}),
is_public: integer('is_public', { mode: 'boolean' }),
activity: text('activity').default('trip'),
bounds: text('bounds', { mode: 'json' }).$type<OfflineMap['bounds']>(),
bounds: text('bounds', { mode: 'json' }).$type<
OfflineMapMetadata['bounds']
>(),
type: text('type').default('trip'),
scores: text('scores', { mode: 'json' })
.$type<Object>()
Expand Down Expand Up @@ -651,3 +655,6 @@ export type Conversation = InferSelectModel<typeof conversation>;
export type InsertConversation = InferInsertModel<typeof conversation>;
export const insertConversationSchema = createInsertSchema(conversation);
export const selectConversationSchema = createSelectSchema(conversation);

export type OfflineMap = InferSelectModel<typeof offlineMap>;
export type InsertOfflineMap = InferInsertModel<typeof offlineMap>;
10 changes: 7 additions & 3 deletions server/src/modules/feed/controllers/getPublicFeed.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { getNextOffset, getPaginationResponse } from 'src/helpers/pagination';
import {
getNextOffset,
getPaginationResponse,
} from '../../../helpers/pagination';
import { protectedProcedure } from '../../../trpc';
import { getFeedService } from '../services';
import { z } from 'zod';
import { FeedQueryBy, PaginationParams } from '../models';

export function getPublicFeedRoute() {
return protectedProcedure
Expand All @@ -18,10 +22,10 @@ export function getPublicFeedRoute() {
.query(async (opts) => {
const { queryBy, searchTerm, excludeType, pagination } = opts.input;
const { data, totalCount, currentPagination } = await getFeedService(
queryBy,
queryBy as FeedQueryBy,
{ searchTerm, isPublic: true },
excludeType,
pagination,
pagination as PaginationParams,
);
return {
data,
Expand Down
7 changes: 4 additions & 3 deletions server/src/modules/feed/controllers/getUserPacksFeed.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { getPaginationResponse } from 'src/helpers/pagination';
import { getPaginationResponse } from '../../../helpers/pagination';
import { protectedProcedure } from '../../../trpc';
import { getFeedService } from '../services';
import { z } from 'zod';
import { FeedQueryBy, PaginationParams } from '../models';

export function getUserPacksFeedRoute() {
return protectedProcedure
Expand All @@ -22,10 +23,10 @@ export function getUserPacksFeedRoute() {
const { queryBy, searchTerm, ownerId, pagination, isPublic, itemId } =
opts.input;
const { data, totalCount, currentPagination } = await getFeedService(
queryBy,
queryBy as FeedQueryBy,
{ searchTerm, ownerId, isPublic, itemId },
'trips',
pagination,
pagination as PaginationParams,
);
return {
data,
Expand Down
7 changes: 4 additions & 3 deletions server/src/modules/feed/controllers/getUserTripsFeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import {
getNextOffset,
getPaginationParams,
getPaginationResponse,
} from 'src/helpers/pagination';
} from '../../../helpers/pagination';
import { protectedProcedure } from '../../../trpc';
import { getFeedService } from '../services';
import { z } from 'zod';
import { FeedQueryBy, PaginationParams } from '../models';

export function getUserTripsFeedRoute() {
return protectedProcedure
Expand All @@ -24,10 +25,10 @@ export function getUserTripsFeedRoute() {
.query(async (opts) => {
const { queryBy, searchTerm, ownerId, pagination, isPublic } = opts.input;
const { data, totalCount, currentPagination } = await getFeedService(
queryBy,
queryBy as FeedQueryBy,
{ searchTerm, ownerId, isPublic },
'packs',
pagination,
pagination as PaginationParams,
);
return {
data,
Expand Down
63 changes: 34 additions & 29 deletions server/src/modules/feed/model/feed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { and, asc, desc, eq, like, sql } from 'drizzle-orm';
import { and, asc, desc, eq, like, sql, SQL } from 'drizzle-orm';
import { DbClient } from '../../../db/client';
import {
item,
Expand All @@ -7,7 +7,7 @@ import {
trip,
userFavoritePacks,
} from '../../../db/schema';
import { literal } from 'src/drizzle/helpers';
import { literal } from '../../../drizzle/helpers';
import {
getPaginationParams,
getPrevOffset,
Expand Down Expand Up @@ -66,7 +66,7 @@ export class Feed {
pagination?: PaginationParams,
) {
try {
let packsQuery = DbClient.instance
let packsQuery: any = DbClient.instance
.select({
id: pack.id,
createdAt: sql`${pack.createdAt} as createdAt`,
Expand All @@ -82,32 +82,35 @@ export class Feed {
quantity: sql`COALESCE(SUM(${itemPacks.quantity}), 0)`,
userFavorites: sql`GROUP_CONCAT(DISTINCT ${userFavoritePacks.userId}) as userFavorites`,
total_weight: sql`COALESCE(SUM(${item.weight} * ${itemPacks.quantity}), 0) as total_weight`,
hasItem: modifiers.itemId
hasItem: modifiers?.itemId
? sql`CASE WHEN COUNT(DISTINCT CASE WHEN ${itemPacks.itemId} = ${modifiers.itemId} THEN 1 ELSE NULL END) > 0 THEN TRUE ELSE FALSE END as hasItem`
: literal(null),
activity: literal(null),
start_date: literal(null),
end_date: literal(null),
: sql`NULL as hasItem`,
activity: sql`NULL as activity`,
start_date: sql`NULL as start_date`,
end_date: sql`NULL as end_date`,
})
.from(pack)
.leftJoin(userFavoritePacks, eq(pack.id, userFavoritePacks.packId))
.leftJoin(itemPacks, eq(pack.id, itemPacks.packId))
.leftJoin(item, eq(itemPacks.itemId, item.id))
.groupBy(pack.id);

if (modifiers.includeUserFavoritesOnly) {
packsQuery = packsQuery.having(
this.generateHavingConditions(modifiers, pack),
);
if (modifiers?.includeUserFavoritesOnly) {
// Cast or conditionally apply .having() only if we have valid conditions
const havingConditions = this.generateHavingConditions(modifiers, pack);
if (havingConditions) {
packsQuery = (packsQuery as any).having(havingConditions as any);
}
}

if (modifiers) {
packsQuery = packsQuery.where(
this.generateWhereConditions(modifiers, pack),
);
const whereConditions = this.generateWhereConditions(modifiers, pack);
if (whereConditions) {
packsQuery = (packsQuery as any).where(whereConditions as any);
}
}

let tripsQuery = DbClient.instance
let tripsQuery: any = DbClient.instance
.select({
id: trip.id,
createdAt: sql`${trip.createdAt} as createdAt`,
Expand All @@ -120,10 +123,10 @@ export class Feed {
description: trip.description,
destination: trip.destination,
favorites_count: literal('0'),
quantity: literal(null),
quantity: sql`NULL as quantity`,
userFavorites: literal('[]'),
total_weight: literal('0'),
hasItem: literal(null),
hasItem: sql`NULL as hasItem`,
activity: trip.activity,
start_date: trip.start_date,
end_date: trip.end_date,
Expand All @@ -137,10 +140,10 @@ export class Feed {
}

if (excludeType === 'packs') {
packsQuery = null;
packsQuery = null as any;
}
if (excludeType === 'trips') {
tripsQuery = null;
tripsQuery = null as any;
}

packsQuery = this.applyPackOrders(
Expand All @@ -149,9 +152,9 @@ export class Feed {
tripsQuery === null,
);

let feedQuery = null;
let feedQuery: any = null;
if (packsQuery && tripsQuery) {
feedQuery = packsQuery.union(tripsQuery);
feedQuery = (packsQuery as any).union(tripsQuery as any);
} else if (packsQuery) {
feedQuery = packsQuery;
} else if (tripsQuery) {
Expand All @@ -170,7 +173,9 @@ export class Feed {
queryBy === 'Most Recent'
? desc(sql`createdAt`)
: asc(sql`createdAt`);
feedQuery = feedQuery.orderBy(order);
if (feedQuery) {
feedQuery = feedQuery.orderBy(order);
}
}

const feedData = await feedQuery.limit(limit).offset(offset).all();
Expand Down Expand Up @@ -251,17 +256,17 @@ export class Feed {
modifiers: Modifiers,
table: typeof trip | typeof pack,
) {
const conditions = [];
const conditions: SQL<unknown>[] = [];

if (modifiers.isPublic !== undefined) {
if (modifiers?.isPublic !== undefined) {
conditions.push(eq(table.is_public, modifiers.isPublic));
}

if (modifiers.ownerId) {
if (modifiers?.ownerId) {
conditions.push(eq(table.owner_id, modifiers.ownerId));
}

if (modifiers.searchTerm) {
if (modifiers?.searchTerm) {
conditions.push(like(table.name, `%${modifiers.searchTerm}%`));
}

Expand All @@ -272,9 +277,9 @@ export class Feed {
modifiers: Modifiers,
table: typeof trip | typeof pack,
) {
const conditions = [];
const conditions: SQL<unknown>[] = [];

if (modifiers.ownerId && modifiers.includeUserFavoritesOnly) {
if (modifiers?.ownerId && modifiers.includeUserFavoritesOnly) {
conditions.push(
sql`userFavorites LIKE CONCAT('%', ${modifiers.ownerId}, '%')`,
);
Expand Down
5 changes: 5 additions & 0 deletions server/src/modules/feed/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ export type FeedQueryBy =
| 'Lightest'
| 'Heaviest'
| 'Oldest';

export interface PaginationParams {
limit: number;
offset: number;
}
6 changes: 3 additions & 3 deletions server/src/modules/feed/services/getFeedService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

import { PaginationParams } from '../../../helpers/pagination';
import { Feed } from '../model';
import { Modifiers } from '../models';
import { Modifiers, FeedQueryBy } from '../models';

/**
* Retrieves public trips based on the given query parameter.
* @param {PrismaClient} prisma - Prisma client.
* @param {string} queryBy - The query parameter to sort the trips.
* @param {FeedQueryBy} queryBy - The query parameter to sort the trips.
* @return {Promise<object[]>} The public trips.
*/
export const getFeedService = async (
queryBy: string,
queryBy: FeedQueryBy,
modifiers?: Modifiers,
excludeType?: 'trips' | 'packs',
pagination?: PaginationParams,
Expand Down
31 changes: 18 additions & 13 deletions server/src/modules/map/controllers/getOfflineMaps.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
import { getPaginationResponse } from 'src/helpers/pagination';
import { getPaginationResponse } from '../../../helpers/pagination';
import { protectedProcedure } from '../../../trpc';
import { getOfflineMapsService } from '../services';
import { z } from 'zod';
import { OfflineMap } from '../../../db/schema';

export function getOfflineMapsRoute() {
return protectedProcedure
.input(
z.object({
ownerId: z.string(),
pagination: z.object({ limit: z.number(), offset: z.number() }),
pagination: z
.object({ limit: z.number(), offset: z.number() })
.strict(),
}),
)
.query(async (opts) => {
const { pagination, ownerId } = opts.input;
const { offlineMaps, totalCount } = await getOfflineMapsService(
ownerId,
pagination,
);
return {
data: offlineMaps,
...getPaginationResponse(pagination, totalCount),
};
});
.query(
async (opts): Promise<{ data: OfflineMap[]; totalCount: number }> => {
const { pagination, ownerId } = opts.input;
const { offlineMaps, totalCount } = await getOfflineMapsService(
ownerId,
pagination as { limit: number; offset: number },
);
return {
data: offlineMaps,
...getPaginationResponse(pagination, Number(totalCount)),
};
},
);
}
5 changes: 4 additions & 1 deletion server/src/modules/map/model/offlineMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ export class OfflineMap {
try {
const newOfflineMap = await DbClient.instance
.insert(offlineMapTable)
.values(data)
.values({
...data,
metadata: data.metadata as any,
})
.returning()
.get();
return newOfflineMap;
Expand Down
Loading

0 comments on commit 74a5dd7

Please sign in to comment.