|
| 1 | +import { Injectable, NotFoundException } from '@nestjs/common'; |
| 2 | +import { PrismaService } from 'nestjs-prisma'; |
| 3 | +import { CreateLocationDto } from './dto/create-location.dto'; |
| 4 | + |
| 5 | +@Injectable() |
| 6 | +export class LocationService { |
| 7 | + constructor(private readonly prisma: PrismaService) {} |
| 8 | + |
| 9 | + /** |
| 10 | + * Creates a Location entry by resolving the provided subscription token to a Subscription row. |
| 11 | + * Mirrors the logic in the Next.js /api/location route (token stored in Subscription.keys JSON). |
| 12 | + */ |
| 13 | + async createFromSubscriptionToken(dto: CreateLocationDto, ipAddress: string) { |
| 14 | + // Find subscription whose JSON `keys` contains the provided token. |
| 15 | + // Prisma JSON partial match: we need to fetch candidates then filter if driver lacks contains helper in generated types. |
| 16 | + // We'll search for any subscription where keys is not null then filter in memory. |
| 17 | + const candidates = await this.prisma.subscription.findMany({ where: { keys: { not: null } } }); |
| 18 | + const subscription = candidates.find((s: any) => s.keys && s.keys.token === dto.subscriptionId); |
| 19 | + |
| 20 | + if (!subscription) { |
| 21 | + throw new NotFoundException('Subscription not found.'); |
| 22 | + } |
| 23 | + |
| 24 | + const newLocation = await this.prisma.location.create({ |
| 25 | + data: { |
| 26 | + subscriptionId: subscription.id, |
| 27 | + ipAddress: ipAddress || 'Unknown', |
| 28 | + accuracy: dto.accuracy, |
| 29 | + altitude: dto.altitude, |
| 30 | + altitudeAccuracy: dto.altitudeAccuracy, |
| 31 | + heading: dto.heading, |
| 32 | + latitude: dto.latitude, |
| 33 | + longitude: dto.longitude, |
| 34 | + speed: dto.speed, |
| 35 | + mocked: dto.mocked ?? false, |
| 36 | + timestamp: dto.timestamp ? BigInt(dto.timestamp) : undefined, |
| 37 | + city: dto.city, |
| 38 | + country: dto.country, |
| 39 | + district: dto.district, |
| 40 | + formattedAddress: dto.formattedAddress, |
| 41 | + isoCountryCode: dto.isoCountryCode, |
| 42 | + name: dto.name, |
| 43 | + postalCode: dto.postalCode, |
| 44 | + region: dto.region, |
| 45 | + street: dto.street, |
| 46 | + streetNumber: dto.streetNumber, |
| 47 | + subregion: dto.subregion, |
| 48 | + timezone: dto.timezone, |
| 49 | + }, |
| 50 | + }); |
| 51 | + |
| 52 | + return newLocation; |
| 53 | + } |
| 54 | +} |
0 commit comments