diff --git a/convex/posts.ts b/convex/posts.ts index 1e04167..278c537 100644 --- a/convex/posts.ts +++ b/convex/posts.ts @@ -1,4 +1,4 @@ -import { PaginationResult, paginationOptsValidator } from 'convex/server'; +import { paginationOptsValidator } from 'convex/server'; import { v } from 'convex/values'; import { PostWithUserDto } from '../src/app/types'; import { Id } from './_generated/dataModel'; @@ -206,7 +206,7 @@ export const getAllPostsWithUser = query({ export const getAllPostsForFollowings = query({ args: { paginationOpts: paginationOptsValidator }, - handler: async (ctx, args): Promise> => { + handler: async (ctx, args) => { const currentUser = await ctx.auth.getUserIdentity(); if (currentUser === null) { @@ -272,3 +272,13 @@ export const getAllPostsForFollowings = query({ return { ...posts, page: postsWithUser }; }, }); + +export const getPostsBySearchTerm = query({ + args: { term: v.string(), paginationOpts: paginationOptsValidator }, + handler: async (ctx, args) => { + return await ctx.db + .query('posts') + .withSearchIndex('search_by_content', q => q.search('content', args.term)) + .paginate(args.paginationOpts); + }, +}); diff --git a/convex/schema.ts b/convex/schema.ts index 8d40c56..3784e03 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -34,14 +34,22 @@ export default defineSchema( created_at: v.number(), updated_at: v.number(), }), - }).index('by_clerk_id', ['clerkUser.id']), + }) + .index('by_clerk_id', ['clerkUser.id']) + .searchIndex('search_by_username', { + searchField: 'clerkUser.username', + }), posts: defineTable({ parentPostId: v.optional(v.id('posts')), userId: v.id('users'), content: v.array(v.string()), }) .index('by_user_id', ['userId']) - .index('by_parent_id', ['parentPostId']), + .index('by_parent_id', ['parentPostId']) + .searchIndex('search_by_content', { + searchField: 'content', + filterFields: ['parentPostId'], + }), likes: defineTable({ postId: v.id('posts'), userId: v.id('users'), diff --git a/convex/users.ts b/convex/users.ts index b90f9c1..8dbb8d6 100644 --- a/convex/users.ts +++ b/convex/users.ts @@ -1,3 +1,4 @@ +import { paginationOptsValidator } from 'convex/server'; import { v } from 'convex/values'; import { UserDto } from './../src/app/types/index'; import { @@ -121,3 +122,15 @@ export const deleteUser = internalMutation({ await ctx.db.delete(userRecord._id); }, }); + +export const getUsersBySearchTerm = query({ + args: { term: v.string(), paginationOpts: paginationOptsValidator }, + handler: async (ctx, args) => { + return await ctx.db + .query('users') + .withSearchIndex('search_by_username', q => + q.search('clerkUser.username', args.term) + ) + .paginate(args.paginationOpts); + }, +});