feat: more work on stores
This commit is contained in:
@ -49,7 +49,9 @@ export const SyncPayload = z.object({
|
||||
id: z.uuid(),
|
||||
operation: z.enum(["create", "update", "delete"]),
|
||||
data: z.string(),
|
||||
modified_at: z.string().refine(val => !isNaN(Date.parse(val)), { message: "Invalid date" })
|
||||
modified_at: z.string().refine(val => !isNaN(Date.parse(val)), { message: "Invalid date" }),
|
||||
type: z.enum(["location", "vehicle", "route"]),
|
||||
name: z.string().min(1).max(100)
|
||||
})),
|
||||
stores: z.array(z.object({
|
||||
id: z.uuid(),
|
||||
@ -59,12 +61,25 @@ export const SyncPayload = z.object({
|
||||
|
||||
export type SyncPayload = z.infer<typeof SyncPayload>;
|
||||
|
||||
// TODO: verify data
|
||||
export async function sync(payload: SyncPayload, user: User) {
|
||||
const changes: Store[] = [];
|
||||
// Apply changes from client
|
||||
for(const change of payload.changes) {
|
||||
const store = await Store.findOneBy({ id: change.id });
|
||||
if(!store) continue;
|
||||
if(!store) {
|
||||
// Store doesn't exist, create it
|
||||
const newStore = new Store();
|
||||
newStore.id = change.id;
|
||||
newStore.user = user;
|
||||
newStore.data = change.data;
|
||||
newStore.modified_at = new Date(change.modified_at);
|
||||
newStore.created_at = new Date();
|
||||
newStore.type = change.type;
|
||||
newStore.name = change.name;
|
||||
await newStore.save();
|
||||
continue;
|
||||
}
|
||||
if(store.user.id !== user.id) {
|
||||
// Not the owner of this store
|
||||
changes.push(store); // Send back the store to the client to overwrite their changes
|
||||
|
||||
Reference in New Issue
Block a user