Skip to content

Commit

Permalink
Merge pull request #1115 from andrew-bierman/server/save-downloaded-m…
Browse files Browse the repository at this point in the history
…ap-in-user-profile

Server: save downloaded map in user profile
  • Loading branch information
andrew-bierman authored Jul 22, 2024
2 parents 8dc6377 + 5bc73bd commit 50e6deb
Show file tree
Hide file tree
Showing 28 changed files with 102 additions and 48 deletions.
16 changes: 16 additions & 0 deletions packages/validations/src/validations/userRoutesValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,22 @@ export const editUser = z.object({
code: z.string().optional(),
role: z.enum(['user', 'admin']).optional(),
username: z.string().optional(),
offlineMaps: z
.record(
z.string(),
z.object({
name: z.string(),
styleURL: z.string(),
metadata: z.object({
shape: z.string(),
}),
bounds: z.array(z.array(z.number())),
minZoom: z.number(),
maxZoom: z.number(),
}),
)
.optional()
.nullable(),
profileImage: z.string().optional().nullable(),
preferredWeather: z.string().optional(),
preferredWeight: z.string().optional(),
Expand Down
1 change: 1 addition & 0 deletions server/migrations/0003_reflective_mimic.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE user ADD `offline_maps` text;
11 changes: 9 additions & 2 deletions server/migrations/meta/0003_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"version": "5",
"dialect": "sqlite",
"id": "139ca60e-e238-46a7-b360-e18f0451c9b7",
"prevId": "79e15743-f558-4a68-bdb3-8220ab3aefe5",
"id": "57e2d274-a728-4d09-9aff-74d3b92399fa",
"prevId": "139ca60e-e238-46a7-b360-e18f0451c9b7",
"tables": {
"conversation": {
"name": "conversation",
Expand Down Expand Up @@ -945,6 +945,13 @@
"notNull": false,
"autoincrement": false
},
"offline_maps": {
"name": "offline_maps",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
Expand Down
7 changes: 7 additions & 0 deletions server/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
"when": 1713116052484,
"tag": "0002_numerous_tyger_tiger",
"breakpoints": true
},
{
"idx": 3,
"version": "5",
"when": 1721509132975,
"tag": "0003_reflective_mimic",
"breakpoints": true
}
]
}
2 changes: 1 addition & 1 deletion server/src/controllers/auth/emailExists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const emailExists = async (c) => {
smtpEmail: c.env.STMP_EMAIL,
email,
});
console.log('emailExists', emailExists)
console.log('emailExists', emailExists);
return c.json({ emailExists }, 200);
} catch (error) {
return c.json({ error: `Failed to delete user: ${error.message}` }, 404);
Expand Down
4 changes: 2 additions & 2 deletions server/src/controllers/getOsm/getPhotonResults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ export async function getPhotonResults(ctx: Context) {
try {
const { searchString } = await ctx.req.query();
const response = await getPhotonResultsService(searchString);
return ctx.json(response.features, 200)
return ctx.json(response.features, 200);
} catch (error) {
return ctx.json({error: error.message}, 500)
return ctx.json({ error: error.message }, 500);
}
}

Expand Down
5 changes: 1 addition & 4 deletions server/src/controllers/item/addGlobalItemToPack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ export const addGlobalItemToPack = async (c: Context) => {
const item = await addGlobalItemToPackService(packId, itemId, ownerId);
return c.json({ item }, 200);
} catch (error) {
return c.json(
{ error: `${error.message}` },
500,
);
return c.json({ error: `${error.message}` }, 500);
}
};

Expand Down
3 changes: 1 addition & 2 deletions server/src/controllers/item/addItemGlobal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import * as validator from '@packrat/validations';

export const addItemGlobal = async (c: Context) => {
try {
const { name, weight, quantity, unit, type, ownerId } =
await c.req.json();
const { name, weight, quantity, unit, type, ownerId } = await c.req.json();

const item = await addItemGlobalService(
name,
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/item/searchItemsByName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { type Context } from 'hono';
export const searchItemsByName = async (c: Context) => {
try {
const { name } = await c.req.query();

const items = await searchItemsByNameService(name);
return c.json({ items }, 200);
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/pack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ export * from './duplicatePublicPack';
export * from './getPackById';
export * from './getPublicPacks';
export * from './scorePack';
export * from './getSimilarPacks';
export * from './getSimilarPacks';
2 changes: 1 addition & 1 deletion server/src/controllers/passport/signInGoogle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const signInGoogle = async (c: Context) => {
if (!decodedToken) {
throw new Error('Invalid ID token');
}
console.log('decodedToken', decodedToken)
console.log('decodedToken', decodedToken);
const {
payload: { email, name, sub: googleId },
} = decodedToken;
Expand Down
3 changes: 3 additions & 0 deletions server/src/controllers/user/editUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ export function editUserRoute() {
profileImage,
preferredWeather,
preferredWeight,
offlineMaps,
} = opts.input;
console.error('failed to logging');
let { password } = opts.input;
const { env }: any = opts.ctx;
const JWT_SECRET = env.JWT_SECRET;
Expand All @@ -74,6 +76,7 @@ export function editUserRoute() {
...(profileImage && { profileImage }),
...(preferredWeather && { preferredWeather }),
...(preferredWeight && { preferredWeight }),
...(offlineMaps && { offlineMaps }),
};
const editedUser = await userClass.update(data);
return editedUser;
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/user/getMe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { protectedProcedure } from '../../trpc';
export const getMe = async (c: Context) => {
try {
const { user } = await c.req.json();
console.log('user ', user)
console.log('user ', user);
return c.json({ user }, 200);
} catch (error) {
return c.json({ error: `Failed to get user: ${error.message}` }, 500);
Expand Down
2 changes: 1 addition & 1 deletion server/src/controllers/user/sentEmail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { type Context } from 'hono';
export const sentEmail = async (c: Context) => {
try {
const { email } = await c.req.json();
console.log('email ', c.env.SEND_GRID_API_KEY)
console.log('email ', c.env.SEND_GRID_API_KEY);
const STMP_EMAIL = c.env.STMP_EMAIL;
const SEND_GRID_API_KEY = c.env.SEND_GRID_API_KEY;
const JWT_SECRET = c.env.JWT_SECRET;
Expand Down
14 changes: 14 additions & 0 deletions server/src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ import {
import { createInsertSchema, createSelectSchema } from 'drizzle-zod';
import { createId } from '@paralleldrive/cuid2';

interface OfflineMap {
name: string;
styleURL: string;
bounds: [number[], number[]];
minZoom: number;
maxZoom: number;
metadata: {
shape: string;
};
}

export const user = sqliteTable('user', {
id: text('id')
.primaryKey()
Expand All @@ -31,6 +42,9 @@ export const user = sqliteTable('user', {
passwordResetTokenExpiration: integer('password_reset_token_expiration', {
mode: 'timestamp',
}),
offlineMaps: text('offline_maps', { mode: 'json' }).$type<
Record<string, OfflineMap>
>(),
role: text('role', { enum: ['admin', 'user'] })
.default('user')
.$type<'admin' | 'user'>(),
Expand Down
2 changes: 1 addition & 1 deletion server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { securityHeaders } from './middleware/securityHeaders';
import { enforceHttps } from './middleware/enforceHttps';
import router from './routes';
import { CORS_METHODS } from './config';
import { Ai } from '@cloudflare/ai';
import { type Ai } from '@cloudflare/ai';
import { httpDBContext } from './trpc/httpDBContext';

interface Bindings {
Expand Down
6 changes: 3 additions & 3 deletions server/src/integrations/ai/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Ai } from "@cloudflare/ai";
import { Ai } from '@cloudflare/ai';

class AiClient {
private static _instance: AiClient | null = null;
private apiKey: string;
private accountId: string;
private readonly apiKey: string;
private readonly accountId: string;
private readonly MODEL_NAME: string = '@cf/baai/bge-base-en-v1.5';
private readonly EXECUTE_AI_MODEL_URL: string;

Expand Down
2 changes: 1 addition & 1 deletion server/src/middleware/checkRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const checkRole = (roles: string[]) => {
// Proceed to the next middleware or route handler.
await next();
} catch (err) {
console.log('error', err)
console.log('error', err);
if (err instanceof ZodError) {
console.error('Invalid role provided:', err.errors);
return c.json({ error: 'Invalid role provided.' }, 400);
Expand Down
16 changes: 16 additions & 0 deletions server/src/middleware/validators/userRoutesValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ export const editUser = z.object({
email: z.string().optional(),
code: z.string().optional(),
role: z.enum(['user', 'admin']).optional(),
offlineMaps: z
.record(
z.string(),
z.object({
name: z.string(),
styleURL: z.string(),
metadata: z.object({
shape: z.string(),
}),
bounds: z.array(z.array(z.number())),
minZoom: z.number(),
maxZoom: z.number(),
}),
)
.optional()
.nullable(),
username: z.string().optional(),
profileImage: z.string().optional(),
preferredWeather: z.string().optional(),
Expand Down
8 changes: 3 additions & 5 deletions server/src/queue/client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import PQueue from 'p-queue';

interface QueueTask<T> {
(): Promise<T>;
}
type QueueTask<T> = () => Promise<T>;

export class Queue {
private static instance: Queue;
private queue: PQueue;
private readonly queue: PQueue;

private constructor(concurrency: number = 1) {
this.queue = new PQueue({ concurrency });
Expand All @@ -22,4 +20,4 @@ export class Queue {
async addTask<T>(task: QueueTask<T>): Promise<T> {
return this.queue.add(task);
}
}
}
4 changes: 2 additions & 2 deletions server/src/queue/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MessageBatch } from '@cloudflare/workers-types';
import { Bindings } from '..';
import { type MessageBatch } from '@cloudflare/workers-types';
import { type Bindings } from '..';

async function handleEtlQueue(batch: MessageBatch<Error>, env: Bindings) {
for (const message of batch.messages) {
Expand Down
4 changes: 2 additions & 2 deletions server/src/services/item/addItemService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const addItemService = async (
packId: string,
type: 'Food' | 'Water' | 'Essentials',
ownerId: string,
executionCtx: ExecutionContext
executionCtx: ExecutionContext,
) => {
let category: InsertItemCategory | null;
if (!categories.includes(type)) {
Expand Down Expand Up @@ -85,4 +85,4 @@ export const addItemService = async (
);

return item;
};
};
5 changes: 2 additions & 3 deletions server/src/services/item/getSimilarItemsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function getSimilarItemsService(
visibility: PackAndItemVisibilityFilter,
) {
const itemObj = new Item();
let item = await itemObj.findItem({
const item = await itemObj.findItem({
id,
});

Expand All @@ -35,8 +35,7 @@ export async function getSimilarItemsService(
visibility == PackAndItemVisibilityFilter.ALL
? undefined
: {
isPublic:
visibility == PackAndItemVisibilityFilter.PUBLIC ? true : false,
isPublic: visibility == PackAndItemVisibilityFilter.PUBLIC,
},
);

Expand Down
1 change: 0 additions & 1 deletion server/src/services/pack/getPublicPacksService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export async function getPublicPacksService(queryBy: string = 'createdAt') {
is_public: true,
});


// Apply sorting if necessary
packs = await sortFunction({
packs,
Expand Down
5 changes: 2 additions & 3 deletions server/src/services/pack/getSimilarPacksService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function getSimilarPacksService(
visibility: PackAndItemVisibilityFilter,
) {
const packClass = new Pack();
let pack = await packClass.findPack({
const pack = await packClass.findPack({
id,
});

Expand All @@ -35,8 +35,7 @@ export async function getSimilarPacksService(
visibility == PackAndItemVisibilityFilter.ALL
? undefined
: {
isPublic:
visibility == PackAndItemVisibilityFilter.PUBLIC ? true : false,
isPublic: visibility == PackAndItemVisibilityFilter.PUBLIC,
},
);

Expand Down
5 changes: 2 additions & 3 deletions server/src/services/user/emailExistsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function emailExistsService({
throw new Error(val);
}
const result1 = await sendEmailNotice({ sendGridApiKey, smtpEmail, email });
console.log('result1result1', result1)
console.log('result1result1', result1);
if (result1.status) {
const { newcode } = result1;
const result2 = await findUserAndUpdate(email, newcode, 'code');
Expand All @@ -27,9 +27,8 @@ export async function emailExistsService({
}
}
} catch (error) {
console.log('error', error.message)
console.log('error', error.message);
throw new Error(error.message);

}
}

Expand Down
2 changes: 1 addition & 1 deletion server/src/tests/routes/pack.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import { Pack as PackClass } from '../../drizzle/methods/pack';
import { User as UserClass } from '../../drizzle/methods/User';
import type { Pack, User } from '../../db/schema';
import { ExecutionContext } from 'hono';
import { type ExecutionContext } from 'hono';

const { mockSyncRecord, mockDeleteVector, mockSearchVector } = vi.hoisted(
() => {
Expand Down
Loading

0 comments on commit 50e6deb

Please sign in to comment.