Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 115 additions & 94 deletions task-2/post-cli/src/services.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,49 @@
// Change base URL for API requests to the local IP of the Post Central API server
const BASE_URL = 'http://localhost:3000';

// ============================================================================
// AUTH TOKEN - Stored after login/register, sent with every request
// ============================================================================

/**
* The JWT token received from login or register.
* This token proves who you are to the server.
*/
let authToken = null;

/**
* Save the token. Called by the UI after login/register and by unit tests.
*/
// ================= TOKEN =================

const setToken = (token) => {
authToken = token;
};

/**
* Get the current token. Use this to build the Authorization header
* for authenticated requests: `Bearer ${getToken()}`
*/
const getToken = () => authToken;

// ============================================================================
// HELLO ENDPOINT - Already implemented! Read this as a reference for your code.
// ============================================================================
// ================= HELLO =================

/**
* Get a hello message from Post Central
* Method: GET | Endpoint: /posts/hello | Auth: No
* Response: { id: number, user: string, text: string, timestamp: string }
*/
const getHello = async () => {
const response = await fetch(`${BASE_URL}/posts/hello`);

if (!response.ok) {
throw new Error(
`Failed to get hello: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

// ============================================================================
// STAGE 1: GET REQUEST - Read data from the server
// ============================================================================
// ================= AUTH =================

/**
* Get current user information
* Method: GET | Endpoint: /users/me | Auth: Yes
* Response: { user: string }
*/
const getMe = async () => {
// TODO
};
const loginUser = async (name, password) => {
const response = await fetch(`${BASE_URL}/users/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, password }),
});

// ============================================================================
// STAGE 2: POST REQUEST - createUser() is provided as a reference. Implement loginUser().
// ============================================================================
if (!response.ok) {
throw new Error(
`Failed to login: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

/**
* Register a new user
* Method: POST | Endpoint: /users/register | Auth: No
* Body: { name, password }
* Response: { user: string, token: string }
*/
const createUser = async (name, password) => {
const response = await fetch(`${BASE_URL}/users/register`, {
method: 'POST',
Expand All @@ -74,78 +52,121 @@ const createUser = async (name, password) => {
},
body: JSON.stringify({ name, password }),
});

if (!response.ok) {
throw new Error(
`Failed to create user: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

/**
* Log in an existing user
* Method: POST | Endpoint: /users/login | Auth: No
* Body: { name, password }
* Response: { user: string, token: string }
*/
const loginUser = async (name, password) => {
// TODO
};
const getMe = async () => {
const response = await fetch(`${BASE_URL}/users/me`, {
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

// ============================================================================
// STAGE 3: More CRUD Operations
// ============================================================================
if (!response.ok) {
throw new Error(
`Failed to get user: HTTP ${response.status} ${response.statusText}`
);
}

/**
* Create a new post
* Method: POST | Endpoint: /posts | Auth: Yes
* Body: { text }
* Response: { id: number, text: string, user: string }
*/
const createPost = async (text) => {
// TODO
return await response.json();
};

/**
* Get all posts for the current user
* Method: GET | Endpoint: /posts/me | Auth: Yes
* Response: Array of { id, text, user }
*/
// ================= POSTS =================

const getPosts = async () => {
// TODO
const response = await fetch(`${BASE_URL}/posts/me`, {
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

if (!response.ok) {
throw new Error(
`Failed to get posts: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

/**
* Update an existing post
* Method: PUT | Endpoint: /posts/:id | Auth: Yes
* Body: { text }
* Response: { id: number, text: string }
*/
const updatePost = async (id, text) => {
// TODO
const createPost = async (text) => {
const response = await fetch(`${BASE_URL}/posts`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
body: JSON.stringify({ text }),
});

if (!response.ok) {
throw new Error(
`Failed to create post: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

/**
* Delete current user
* Method: DELETE | Endpoint: /users/me | Auth: Yes
* Response: { user: string, message: string }
*/
const deleteUser = async () => {
// TODO
const updatePost = async (id, text) => {
const response = await fetch(`${BASE_URL}/posts/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
body: JSON.stringify({ text }),
});

if (!response.ok) {
throw new Error(
`Failed to update post: HTTP ${response.status} ${response.statusText}`
);
}

return await response.json();
};

/**
* Delete a post
* Method: DELETE | Endpoint: /posts/:id | Auth: Yes
* Response: { id: number, text: string, message: string }
*/
const deletePost = async (id) => {
// TODO
const response = await fetch(`${BASE_URL}/posts/${id}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

if (!response.ok) {
throw new Error(
`Failed to delete post: HTTP ${response.status} ${response.statusText}`
);
}
};

// ================= USER DELETE =================

const deleteUser = async () => {
const response = await fetch(`${BASE_URL}/users/me`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${getToken()}`,
},
});

if (!response.ok) {
throw new Error(
`Failed to delete user: HTTP ${response.status} ${response.statusText}`
);
}
};

// ============================================================================
// EXPORTS - Make functions available for testing and main.js
// ============================================================================
// ================= EXPORTS =================

export {
createPost,
Expand Down