post.js
2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as auth from '../auth'
import axios from 'axios';
import { SERVER_BASE_URL } from '..';
import { useSession } from 'next-auth/client';
export const newPost = async (
title,
explain,
example,
testinput,
testoutput,
difficulty,
) => {
if (!auth.validateToken()) {
throw alert("Please login first.");
}
const response = await axios.post(`${SERVER_BASE_URL}/post`, {
token: auth.getToken(),
title,
explain,
example,
testinput,
testoutput,
difficulty,
});
if (response.status !== 200 && response.status !== 201) {
throw new Error('Failed to create new post!');
}
return response.data.id;
}
export const getPostbyId = async (id) => {
const response = await axios.get(`${SERVER_BASE_URL}/post/id/${id}`);
if (response.status !== 200) {
throw new Error('Failed to get post!');
}
return response.data;
}
export const getPosts = async (takes) => {
const response = await axios.get(`${SERVER_BASE_URL}/post`, {
params: {
takes,
},
});
if (response.status !== 200) {
throw new Error('Failed to get posts!');
}
return response.data;
}
export const getPostsByDifficulty = async (difficulty) => {
const response = await axios.get(`${SERVER_BASE_URL}/post/difficulty/${difficulty}`);
if (response.status !== 200) {
throw new Error('Failed to get posts!');
}
console.log(response.data);
return response.data;
}
export const createComment = async (id, content) => {
if (!await auth.validateToken()) {
throw alert("Please login first.");
}
const response = await axios.post(`${SERVER_BASE_URL}/post/comment/${id}`, {
token : useSession.accessToken,
content,
});
if (response.status !== 200 && response.status !== 201) {
throw new Error('Failed to create comment!');
}
return response.data;
}
export const searchPost = async (search) => {
const response = await axios.post(`${SERVER_BASE_URL}/post/search/`, {
search,
});
if (response.status !== 200 && response.status !== 201) {
throw new Error('Failed to get posts!');
}
return response.data;
}