Skip to content

Commit

Permalink
Merge pull request #21 from Winguweb/fix-polling-dates
Browse files Browse the repository at this point in the history
Fix polling dates
  • Loading branch information
valentinarau authored Mar 7, 2024
2 parents 03af335 + b8a789f commit 475f665
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 14 deletions.
4 changes: 2 additions & 2 deletions pages/api/devices/samples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import availableMethodsHandler from '../../../utils/availableMethodsHandler';
import { onSampleUpload } from '../../../server/notifier/appNotifierService';
import { prismaClient } from '../../../server/prisma/client';
import { nowWithTimezone } from '../../../utils/dates';
import moment from 'moment';

const availableMethods = ['POST'];

Expand All @@ -25,7 +25,7 @@ async function postHandler(req: NextApiRequest, res: NextApiResponse): Promise<v
try {
const splitData = (req.body as string).split(';');
const [id, date, latitude, longitude] = splitData
const timestamp = nowWithTimezone();
const timestamp = moment(date, "YYYY-MM-DD h:mm:ss").toDate();
try {
const device = (await prismaClient.device.findUnique({
where: {
Expand Down
4 changes: 2 additions & 2 deletions pages/api/external-samples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import availableMethodsHandler from "../../../utils/availableMethodsHandler";
import { prismaClient } from "../../../server/prisma/client";
import { createConfirmationTokenAWSSchema } from "../../../model/confirmationTokenAWS";
import { ZodError, z } from "zod";
import { atStartOfHoursAgoISO } from "../../../utils/dates";
import { atStartOfHoursAgo, atStartOfHoursAgoISO } from '../../../utils/dates';

const handler: NextApiHandler = async (req, res) => {
if (!availableMethodsHandler(req, res, ['POST', 'GET'])) {
Expand Down Expand Up @@ -47,7 +47,7 @@ const handler: NextApiHandler = async (req, res) => {
samples = await prismaClient.sample.findMany({
where: {
takenAt: {
gte: atStartOfHoursAgoISO(3),
gte: atStartOfHoursAgo(3),
},
},
select: {
Expand Down
11 changes: 7 additions & 4 deletions pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async (
try {
const googleMapsApiKey = process.env.GOOGLE_MAPS_API_KEY;
const webSocketURL = process.env.WEBSOCKET_URL;
const currentBoats = await fetchBoats();
const currentBoats = await fetchBoats(process.env.BASE_URL);

if (!googleMapsApiKey) {
throw new Error('Environment variable not set: GOOGLE_MAPS_API_KEY');
Expand Down Expand Up @@ -66,6 +66,8 @@ const getMapPosition = (coords: Coordinates | undefined): MapPosition => {
};

const parseBoat = (deviceSample: any): Boat => {
console.log(moment(deviceSample.takenAt, 'YYYY-MM-DD HH:mm'))

return {
id: deviceSample.deviceId,
coordinates: { lat: deviceSample.latitude, lng: deviceSample.longitude },
Expand All @@ -74,8 +76,8 @@ const parseBoat = (deviceSample: any): Boat => {
};
};

const fetchBoats = async () => {
const data = await axios.get(`${process.env.BASE_URL}/api/external-samples?lastHour=true`, {});
const fetchBoats = async (baseUrl: any) => {
const data = await axios.get(`${baseUrl}/api/external-samples?lastHour=true`, {});
return JSON.parse(JSON.stringify(
data.data.samples.map((sample: any) => parseBoat({ ...sample, name: sample.device.name }))));
};
Expand Down Expand Up @@ -112,8 +114,9 @@ const MapWithVehicles: NextPage<ServerSideProps> = ({

useEffect(() => {
const interval = setInterval(async () => {
const newBoats = await fetchBoats()
const newBoats = await fetchBoats("")
setBoats(newBoats)
console.log(newBoats)
}, 20000);
return () => clearInterval(interval);
}, []);
Expand Down
12 changes: 6 additions & 6 deletions server/notifier/appNotifierService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { DeviceCoordinates } from './deviceCoordinates';
import { prismaClient } from '../prisma/client';
import { computeDistanceBetween } from 'spherical-geometry-js';
import { MIN_DISTANCE } from './notifierConfig';
import { nowWithTimezone, todayAtStartOfDayWithTimezone } from '../../utils/dates';
import { sendWhatsappNotification } from './whatsappService';
import moment from 'moment';

const http = axios.create({
baseURL: process.env.NOTIFIER_URL,
Expand Down Expand Up @@ -33,7 +33,7 @@ export async function onSampleUpload(sample: Sample) {
);
return res.data;
} catch (err: any) {
console.error('[NotifierService] error:', err);
console.error('[NotifierService] error');
}
}

Expand All @@ -43,12 +43,12 @@ async function authenticate() {
const res = await http.post('/auth', body);
return res.data.token;
} catch (err: any) {
console.error('[NotifierService][Auth] error:', err);
console.error('[NotifierService][Auth] error');
}
}

async function findUsersToNotify(coords: DeviceCoordinates) {
const firstHourToday = todayAtStartOfDayWithTimezone();
const firstHourToday = moment().startOf('day').format();
const users = await prismaClient.notifyOrder.findMany({
where: {
OR: [
Expand All @@ -74,15 +74,15 @@ async function findUsersToNotify(coords: DeviceCoordinates) {
usersNotified.push(user.id);
}
});
const today = nowWithTimezone();
const now = moment().format();
await prismaClient.notifyOrder.updateMany({
where: {
id: {
in: usersNotified,
},
},
data: {
lastNotifiedAt: today,
lastNotifiedAt: now,
},
});
}
4 changes: 4 additions & 0 deletions utils/dates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ export function todayAtStartOfDayWithTimezone() {

export function atStartOfHoursAgoISO(hours: number) {
return moment().startOf('hour').subtract(hours, 'hour').toISOString();
}

export function atStartOfHoursAgo(hours: number) {
return moment().startOf('hour').subtract(hours, 'hour').format();
}

0 comments on commit 475f665

Please sign in to comment.