|
| 1 | +import { v } from "convex/values"; |
| 2 | +import { api, internal } from "./_generated/api.js"; |
| 3 | +import type { Doc, Id } from "./_generated/dataModel.js"; |
| 4 | +import { |
| 5 | + action, |
| 6 | + internalAction, |
| 7 | + internalMutation, |
| 8 | + internalQuery, |
| 9 | + mutation, |
| 10 | + query, |
| 11 | +} from "./_generated/server.js"; |
| 12 | +import { stream, mergedStream } from "convex-helpers/server/stream"; |
| 13 | +import schema from "./schema.js"; |
| 14 | +import { paginationOptsValidator } from "convex/server"; |
| 15 | + |
| 16 | +export const getInbox = query({ |
| 17 | + args: { |
| 18 | + id: v.string(), |
| 19 | + paginationOpts: paginationOptsValidator, |
| 20 | + }, |
| 21 | + handler: async (ctx, args) => { |
| 22 | + const messages = await stream(ctx.db, schema) |
| 23 | + .query("privateMessages") |
| 24 | + .withIndex("to", (q) => q.eq("to", args.id)) |
| 25 | + .order("desc") |
| 26 | + .paginate(args.paginationOpts); |
| 27 | + return messages; |
| 28 | + }, |
| 29 | +}); |
| 30 | + |
| 31 | +export const getOutbox = query({ |
| 32 | + args: { |
| 33 | + id: v.string(), |
| 34 | + paginationOpts: paginationOptsValidator, |
| 35 | + }, |
| 36 | + handler: async (ctx, args) => { |
| 37 | + const messages = await ctx.db |
| 38 | + .query("privateMessages") |
| 39 | + .withIndex("from", (q) => q.eq("from", args.id)) |
| 40 | + .order("desc") |
| 41 | + .paginate(args.paginationOpts); |
| 42 | + return messages; |
| 43 | + }, |
| 44 | +}); |
| 45 | + |
| 46 | +export const getMessagesBetween = query({ |
| 47 | + args: { |
| 48 | + a: v.string(), |
| 49 | + b: v.string(), |
| 50 | + paginationOpts: paginationOptsValidator, |
| 51 | + }, |
| 52 | + handler: async (ctx, args) => { |
| 53 | + const aToB = stream(ctx.db, schema) |
| 54 | + .query("privateMessages") |
| 55 | + .withIndex("from_to", (q) => q.eq("from", args.a).eq("to", args.b)) |
| 56 | + .order("desc"); |
| 57 | + const bToA = stream(ctx.db, schema) |
| 58 | + .query("privateMessages") |
| 59 | + .withIndex("from_to", (q) => q.eq("from", args.b).eq("to", args.a)) |
| 60 | + .order("desc"); |
| 61 | + |
| 62 | + // Both indexes have the "sentAt" field after the fields they're doing |
| 63 | + // equality on, so they're both sorted by "sentAt" descending, so they |
| 64 | + // can be merged together. |
| 65 | + const messages = await mergedStream([aToB, bToA], ["sentAt"]).paginate( |
| 66 | + args.paginationOpts, |
| 67 | + ); |
| 68 | + return messages; |
| 69 | + }, |
| 70 | +}); |
| 71 | + |
| 72 | +export const sendMessage = mutation({ |
| 73 | + args: { |
| 74 | + from: v.string(), |
| 75 | + to: v.string(), |
| 76 | + message: v.string(), |
| 77 | + }, |
| 78 | + handler: async (ctx, args) => { |
| 79 | + await ctx.db.insert("privateMessages", { |
| 80 | + from: args.from, |
| 81 | + to: args.to, |
| 82 | + message: args.message, |
| 83 | + sentAt: Date.now(), |
| 84 | + }); |
| 85 | + }, |
| 86 | +}); |
0 commit comments