feat: friend system + shared stores
This commit is contained in:
@ -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 };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user