| import type { Session } from "@api/utils/auth"; |
| import { replicationCache } from "@midday/cache/replication-cache"; |
| import type { Database, DatabaseWithPrimary } from "@midday/db/client"; |
|
|
| |
| |
| |
| |
| export const withPrimaryReadAfterWrite = async <TReturn>(opts: { |
| ctx: { |
| session?: Session | null; |
| teamId?: string | null; |
| db: Database; |
| forcePrimary?: boolean; |
| }; |
| type: "query" | "mutation" | "subscription"; |
| next: (opts: { |
| ctx: { |
| session?: Session | null; |
| teamId?: string | null; |
| db: Database; |
| forcePrimary?: boolean; |
| }; |
| }) => Promise<TReturn>; |
| }) => { |
| const { ctx, type, next } = opts; |
| const teamId = ctx.teamId; |
| const forcePrimary = ctx.forcePrimary; |
|
|
| |
| |
| if (forcePrimary && type !== "mutation") { |
| const dbWithPrimary = ctx.db as DatabaseWithPrimary; |
| if (dbWithPrimary.usePrimaryOnly) { |
| ctx.db = dbWithPrimary.usePrimaryOnly(); |
| } |
| const result = await next({ ctx }); |
| return result; |
| } |
|
|
| if (teamId) { |
| |
| if (type === "mutation") { |
| await replicationCache.set(teamId); |
|
|
| |
| const dbWithPrimary = ctx.db as DatabaseWithPrimary; |
| if (dbWithPrimary.usePrimaryOnly) { |
| ctx.db = dbWithPrimary.usePrimaryOnly(); |
| } |
| |
| } |
| |
| else { |
| const timestamp = await replicationCache.get(teamId); |
| const now = Date.now(); |
|
|
| |
| if (timestamp && now < timestamp) { |
| |
| const dbWithPrimary = ctx.db as DatabaseWithPrimary; |
| if (dbWithPrimary.usePrimaryOnly) { |
| ctx.db = dbWithPrimary.usePrimaryOnly(); |
| } |
| |
| } |
| } |
| } else { |
| |
| const dbWithPrimary = ctx.db as DatabaseWithPrimary; |
| if (dbWithPrimary.usePrimaryOnly) { |
| ctx.db = dbWithPrimary.usePrimaryOnly(); |
| } |
| |
| } |
|
|
| const result = await next({ ctx }); |
|
|
| return result; |
| }; |
|
|