diff --git a/apps/backend/package.json b/apps/backend/package.json index de2bcccc..9981d20f 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -14,9 +14,11 @@ "dependencies": { "@mixan/types": "workspace:*", "@prisma/client": "^5.4.2", + "@types/ramda": "^0.29.6", "express": "^4.18.2", "morgan": "^1.10.0", "prisma": "^5.4.2", + "ramda": "^0.29.1", "random-animal-name": "^0.1.1", "uuid": "^9.0.1" }, diff --git a/apps/backend/src/routes/events.ts b/apps/backend/src/routes/events.ts index 79f2a044..1fc3a891 100644 --- a/apps/backend/src/routes/events.ts +++ b/apps/backend/src/routes/events.ts @@ -1,11 +1,12 @@ -import {NextFunction, Response, Router} from 'express' -import { db } from '../db'; -import { MixanRequest } from '../types/express'; -import { EventPayload } from '@mixan/types'; -import { getEvents } from '../services/event'; -import { success } from '../responses/success'; - -const router = Router(); +import { NextFunction, Response, Router } from 'express' +import { db } from '../db' +import { MixanRequest } from '../types/express' +import { EventPayload } from '@mixan/types' +import { getEvents } from '../services/event' +import { success } from '../responses/success' +import { getProfile } from '../services/profile' +import { uniq } from 'ramda' +const router = Router() type PostRequest = MixanRequest> @@ -18,24 +19,48 @@ router.get('/events', async (req, res, next) => { } }) -router.post('/events', async (req: PostRequest, res: Response, next: NextFunction) => { - try { - const projectId = req.client.project_id - - await db.event.createMany({ - data: req.body.map((event) => ({ - name: event.name, - properties: event.properties, - createdAt: event.time, - project_id: projectId, - profile_id: event.profileId, - })) - }) - - res.status(201).json(success()) - } catch (error) { - next(error) - } -}) +router.post( + '/events', + async (req: PostRequest, res: Response, next: NextFunction) => { + try { + const projectId = req.client.project_id -export default router \ No newline at end of file + const profileIds = uniq( + req.body + .map((event) => event.profileId) + .filter((id): id is string => !!id) + ) + + for (const profileId of profileIds) { + try { + await getProfile(profileId) + } catch (error) { + console.log('Profile not found, create it', profileId) + await db.profile.create({ + data: { + project_id: projectId, + id: profileId, + properties: {}, + }, + }) + } + } + + await db.event.createMany({ + data: req.body.map((event) => ({ + name: event.name, + properties: event.properties, + createdAt: event.time, + project_id: projectId, + profile_id: event.profileId, + })), + }) + + res.status(201).json(success()) + } catch (error) { + next(error) + } + } +) + +export default router diff --git a/bun.lockb b/bun.lockb index 17680273..17fe77a8 100755 Binary files a/bun.lockb and b/bun.lockb differ