feat: friend system + shared stores
Some checks failed
TrafficCue Server CI / check (push) Failing after 56s
TrafficCue Server CD / build (push) Successful in 2m5s

This commit is contained in:
2025-10-03 14:13:31 +02:00
parent aff447e741
commit c492e62d60
5 changed files with 247 additions and 7 deletions

View File

@ -1,6 +1,7 @@
import z from "zod";
import { Store, type StoreType } from "./entities/Stores";
import type { User } from "./entities/User";
import { getFriends } from "./entities/Follow";
export const locationStore = z
.object({
@ -53,6 +54,8 @@ export const storeTypes: Record<StoreType, z.ZodSchema> = {
route: routeStore,
};
const sharedStoreTypes: StoreType[] = ["vehicle"];
export const SyncPayload = z.object({
changes: z.array(
z.object({
@ -127,14 +130,44 @@ export async function sync(payload: SyncPayload, user: User) {
await store.save();
}
const friends = await getFriends(user);
const selector = [{ id: user.id }];
for (const friend of friends) {
selector.push({ id: friend.id });
}
// Find stores that are out of date on the client
const allStores = await Store.findBy({ user: { id: user.id } }); // TODO: include friends' public stores, TODO: use SQL query to only get modified stores
const allStores = await Store.find({ where: { user: selector }, relations: { user: true } }); // TODO: use SQL query to only get modified stores
for (const store of allStores) {
if (store.user.id !== user.id && !sharedStoreTypes.includes(store.type)) {
// Not the owner of this store and not a shared type
continue;
}
const clientStore = payload.stores.find((s) => s.id === store.id);
if (!clientStore || new Date(clientStore.modified_at) < store.modified_at) {
changes.push(store); // Client doesn't have this store or it's out of date
}
}
// Send "null" change for stores that aren't owned by the user or their friends
for (const clientStore of payload.stores) {
if (
!allStores.find((s) => s.id === clientStore.id) &&
(!user.id ||
!friends.find((f) => f.id === clientStore.id)) // Not owned by user or their friends
) {
const deletedStore = new Store();
deletedStore.id = clientStore.id;
deletedStore.data = "null";
deletedStore.modified_at = new Date();
deletedStore.created_at = new Date();
deletedStore.type = "location"; // Type doesn't matter, data is null
deletedStore.name = "";
changes.push(deletedStore);
}
}
return { changes };
}