diff --git a/server/src/resolvers/post.ts b/server/src/resolvers/post.ts index 800516ce..73fad6ee 100644 --- a/server/src/resolvers/post.ts +++ b/server/src/resolvers/post.ts @@ -7,10 +7,12 @@ import { Field, Ctx, UseMiddleware, + Int, } from "type-graphql"; import { Post } from "../entities/Post"; import { MyContext } from "../types"; import { isAuth } from "../middleware/isAuth"; +import { getConnection } from "typeorm"; @InputType() class PostInput { @@ -23,8 +25,24 @@ class PostInput { @Resolver() export class PostResolver { @Query(() => [Post]) - async posts(): Promise { - return Post.find(); + async posts( + @Arg("limit", () => Int) limit: number, + @Arg("cursor", () => String, { nullable: true }) cursor: string | null + ): Promise { + const realLimit = Math.min(50, limit); + const qb = getConnection() + .getRepository(Post) + .createQueryBuilder("p") + .orderBy('"createdAt"', "DESC") + .take(realLimit); + + if (cursor) { + qb.where('"createdAt" < :cursor', { + cursor: new Date(parseInt(cursor)), + }); + } + + return qb.getMany(); } @Query(() => Post, { nullable: true }) diff --git a/web/src/generated/graphql.tsx b/web/src/generated/graphql.tsx index e5122b74..407a4134 100644 --- a/web/src/generated/graphql.tsx +++ b/web/src/generated/graphql.tsx @@ -21,6 +21,12 @@ export type Query = { }; +export type QueryPostsArgs = { + cursor?: Maybe; + limit: Scalars['Int']; +}; + + export type QueryPostArgs = { id: Scalars['Float']; }; @@ -222,7 +228,10 @@ export type MeQuery = ( )> } ); -export type PostsQueryVariables = Exact<{ [key: string]: never; }>; +export type PostsQueryVariables = Exact<{ + limit: Scalars['Int']; + cursor?: Maybe; +}>; export type PostsQuery = ( @@ -336,8 +345,8 @@ export function useMeQuery(options: Omit, 'q return Urql.useQuery({ query: MeDocument, ...options }); }; export const PostsDocument = gql` - query Posts { - posts { + query Posts($limit: Int!, $cursor: String) { + posts(cursor: $cursor, limit: $limit) { id createdAt updatedAt diff --git a/web/src/graphql/queries/posts.graphql b/web/src/graphql/queries/posts.graphql index fca043f6..40bad17d 100644 --- a/web/src/graphql/queries/posts.graphql +++ b/web/src/graphql/queries/posts.graphql @@ -1,5 +1,5 @@ -query Posts { - posts { +query Posts($limit: Int!, $cursor: String) { + posts(cursor: $cursor, limit: $limit) { id createdAt updatedAt diff --git a/web/src/pages/index.tsx b/web/src/pages/index.tsx index ff36fe76..6cb0d20f 100644 --- a/web/src/pages/index.tsx +++ b/web/src/pages/index.tsx @@ -7,7 +7,11 @@ import { Link } from "@chakra-ui/core"; import NextLink from "next/link"; const Index = () => { - const [{ data }] = usePostsQuery(); + const [{ data }] = usePostsQuery({ + variables: { + limit: 10, + }, + }); return (