diff --git a/server/src/controllers/index.ts b/server/src/controllers/index.ts index b053586..cec05c4 100644 --- a/server/src/controllers/index.ts +++ b/server/src/controllers/index.ts @@ -1,9 +1,65 @@ +interface Post { + id: number + title: string + reactions: { likes: number; dislikes: number } + tags: string[] + userId: number + imageUrl: string +} + type GetPostsParams = { - query: { - cursor: string - limit: number + query: { skip?: string; limit?: string } +} + +type UpdatePostParams = { + params: { id: number } + body: Post +} + +type CreatePostParams = { + body: Omit +} + +const baseUrl = 'https://dummyjson.com' + +export const getPosts = async ({ query: { skip, limit } }: GetPostsParams): Promise => { + const response = await fetch(`${baseUrl}/posts?skip=${skip || 0}&limit=${limit || 10}`) + const data = await response.json() + + return { + ...data, + posts: data.posts.map((post: Post) => ({ + ...post, + imageUrl: `https://picsum.photos/seed/${post.id}/800/600` + })) } } -export const getPosts = async ({ query: { cursor, limit } }: GetPostsParams) => { - console.log(cursor, limit) +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +export const createPost = async ({ body: post }: CreatePostParams): Promise => { + await sleep(5000) + const response = await fetch(`${baseUrl}/posts/add`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(post) + }) + const data = await response.json() + return { + ...data, + imageUrl: `https://picsum.photos/seed/${data.id}/800/600` + } +} + +export const updatePost = async ({ body: post, params: { id } }: UpdatePostParams): Promise => { + await sleep(5000) + const response = await fetch(`${baseUrl}/posts/${id}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(post) + }) + const data = await response.json() + return { + ...data, + imageUrl: `https://picsum.photos/seed/${data.id}/800/600` + } } diff --git a/server/src/routes/index.ts b/server/src/routes/index.ts index 9f3b8ff..96c7e0f 100644 --- a/server/src/routes/index.ts +++ b/server/src/routes/index.ts @@ -1,10 +1,27 @@ import { Elysia, t } from 'elysia' -import { getPosts } from '@/controllers' +import { createPost, getPosts, updatePost } from '@/controllers' -export const postRoutes = new Elysia({ prefix: '/posts' }).get('/', getPosts, { +export const postRoutes = new Elysia({ prefix: '/posts' }) // - query: t.Object({ - skip: t.Optional(t.String()), - limit: t.Optional(t.Number()) + .get('/', getPosts, { + query: t.Object({ + skip: t.Optional(t.String()), + limit: t.Optional(t.String()) + }) + }) + .post('/', createPost, { + body: t.Object({ + title: t.String(), + body: t.String(), + userId: t.Number(), + tags: t.Array(t.String()) + }) + }) + .put('/:id', updatePost, { + body: t.Object({ + title: t.String(), + body: t.String(), + tags: t.Array(t.String()), + userId: t.Number() + }) }) -})