--- id: 5a8b073d06fa14fcfde687aa title: Трекер вправ challengeType: 4 forumTopicId: 301505 dashedName: exercise-tracker --- # --description-- Створіть full stack додаток на JavaScript, який функціонально схожий до цього: . Робота над цим проектом залучатиме тебе писати свій код використовуючи один з наступних методів: - Клонувати [цей репозиторій з GitHub](https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/) та локально завершити свій проект. - Використати [наш проект для початківців на Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-exercisetracker) для завершення свого проекту. - Використати конструктор сайтів на свій вибір для завершення проекту. Впевніться, що ви зберегли всі файли із нашого GitHub репозиторію. По завершенню переконайтеся, що працююча демоверсія вашого проекту розміщена у відкритому доступі. Потім введіть його URL-адресу в поле `Solution Link`. За бажанням також можете ввести посилання на вихідний код вашого проекту в полі `GitHub Link`. # --instructions-- Ваші відповіді повинні мати наступні структури. Вправа: ```js { username: "fcc_test", description: "test", duration: 60, date: "Mon Jan 01 1990", _id: "5fb5853f734231456ccb3b05" } ``` Користувач: ```js { username: "fcc_test", _id: "5fb5853f734231456ccb3b05" } ``` Лог: ```js { username: "fcc_test", count: 1, _id: "5fb5853f734231456ccb3b05", log: [{ description: "test", duration: 60, date: "Mon Jan 01 1990", }] } ``` **Підказка:** для отримування очікуваного результату властивості `date` може використовуватися метод `toDateString` з `Date` API. # --hints-- Вам необхідно вказати свій власний проект, а не приклад URL-адреси. ```js (getUserInput) => { const url = getUserInput('url'); assert( !/.*\/exercise-tracker\.freecodecamp\.rocks/.test(getUserInput('url')) ); }; ``` Ви можете виконати `POST` запит до `/api/users` з даними форми `username` для створення нового користувача. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); assert.isTrue(res.ok); if(!res.ok) { throw new Error(`${res.status} ${res.statusText}`) }; }; ``` Отримана відповідь від `POST /api/users` з даними форми `username` буде об'єктом з властивостями `username` та `_id`. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); assert.exists(_id); assert.exists(username); } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` Ви можете зробити запит `GET` на `/api/users`, щоб отримати список всіх користувачів. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users'); assert.isTrue(res.ok); if(!res.ok) { throw new Error(`${res.status} ${res.statusText}`) }; }; ``` Запит `GET` на `/api/users` повертає масив. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users'); if(res.ok){ const users = await res.json(); assert.isArray(users); } else { throw new Error(`${res.status} ${res.statusText}`); }; }; ``` Кожен елемент у масиві, який повернувся з `GET /api/users`, є літералом об'єкта з `username` та `_id` користувача. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users'); if(res.ok){ const users = await res.json(); const user = users[0]; assert.exists(user); assert.exists(user.username); assert.exists(user._id); assert.isString(user.username); assert.isString(user._id); } else { throw new Error(`${res.status} ${res.statusText}`); }; }; ``` Ви можете виконати `POST` запит до `/api/users/:_id/exercises` з даними форм `description`, `duration` та за бажанням `date`. Якщо дата не вказана, буде використовуватись поточна дата. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: 'Mon Jan 01 1990' }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}&date=1990-01-01` }); assert.isTrue(addRes.ok); if(!addRes.ok) { throw new Error(`${addRes.status} ${addRes.statusText}`) }; } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` Відповідь, що повернулася від `POST /api/users/:_id/exercises`, буде об'єктом користувача з доданими полями з вправи. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: 'Mon Jan 01 1990' }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}&date=1990-01-01` }); if (addRes.ok) { const actual = await addRes.json(); assert.deepEqual(actual, expected); assert.isString(actual.description); assert.isNumber(actual.duration); assert.isString(actual.date); } else { throw new Error(`${addRes.status} ${addRes.statusText}`); } } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` Ви можете зробити запит `GET` на `/api/users/:_id/logs`, щоб отримати повний журнал вправ будь-якого користувача. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}` }); if (addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); assert.isTrue(logRes.ok); if(!logRes.ok) { throw new Error(`${logRes.status} ${logRes.statusText}`) }; } else { throw new Error(`${addRes.status} ${addRes.statusText}`); } } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` Запит до журналу користувача `GET /api/users/:_id/logs` повертає об'єкт користувача разом з властивістю `count` яка представляє кількість вправ, що належать цьому користувачеві. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}` }); if (addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); if (logRes.ok) { const { count } = await logRes.json(); assert(count); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } } else { throw new Error(`${addRes.status} ${addRes.statusText}`); } } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` Запит `GET` на `/api/users/:id/logs` поверне об'єкт користувача з `log`, - масивом всіх доданих вправ. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }) if(res.ok){ const {_id, username} = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}` }); if(addRes.ok){ const logRes = await fetch(url + `/api/users/${_id}/logs`); if(logRes.ok) { const {log} = await logRes.json(); assert.isArray(log); assert.equal(1, log.length); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } } else { throw new Error(`${addRes.status} ${addRes.statusText}`); }; } else { throw new Error(`${res.status} ${res.statusText}`) }; }; ``` Кожен елемент у масиві `log`, який повернувся з `GET /api/users/:id/logs` це об'єкт, який повинен мати `description` `duration` і `date` властивості. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + `/api/users`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if(res.ok) { const {_id, username} = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}` }); if(addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); if(logRes.ok) { const {log} = await logRes.json(); const exercise = log[0]; assert.exists(exercise); assert.exists(exercise.description); assert.exists(exercise.duration); assert.exists(exercise.date); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); }; } else { throw new Error(`${addRes.status} ${addRes.statusText}`); }; } else { throw new Error(`${res.status} ${res.statusText}`) }; }; ``` Властивість `description` будь-якого об'єкту в масиві `log`, що повернувся з `GET /api/users/:id/logs` повинен бути рядкового типу. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `username=fcc_test_${Date.now()}`.substr(0,29) }); if(res.ok) { const {_id, username} = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `description=${expected.description}&duration=${expected.duration}` }); if(addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); if(logRes.ok){ const {log} = await logRes.json(); const exercise = log[0]; assert.isString(exercise.description); assert.equal(exercise.description, expected.description); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } } else { throw new Error(`${addRes.status} ${addRes.statusText}`); }; } else { throw new Error(`${res.status} ${res.statusText}`); }; }; ``` Властивість `duration` будь-якого об'єкту в масиві `log`, що повернувся з `GET /api/users/:id/logs`, повинна бути числового типу. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `username=fcc_test_${Date.now()}`.substr(0,29) }); if(res.ok) { const {_id, username} = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `description=${expected.description}&duration=${expected.duration}` }); if(addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); if(logRes.ok){ const {log} = await logRes.json(); const exercise = log[0]; assert.isNumber(exercise.duration); assert.equal(exercise.duration, expected.duration); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } } else { throw new Error(`${addRes.status} ${addRes.statusText}`); }; } else { throw new Error(`${res.status} ${res.statusText}`); }; }; ``` Властивість `date` будь-якого об'єкту в масиві `log`, що повернувся з `GET /api/users/:id/logs`, повинна бути рядкового типу.. Використовуйте `dateString` формат з `Date` API. ```js async(getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `username=fcc_test_${Date.now()}`.substr(0,29) }); if(res.ok) { const {_id, username} = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `description=${expected.description}&duration=${expected.duration}` }); if(addRes.ok) { const logRes = await fetch(url + `/api/users/${_id}/logs`); if(logRes.ok){ const {log} = await logRes.json(); const exercise = log[0]; assert.isString(exercise.date); assert.equal(exercise.date, expected.date); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } } else { throw new Error(`${addRes.status} ${addRes.statusText}`); }; } else { throw new Error(`${res.status} ${res.statusText}`); }; }; ``` Ви можете додати параметри `from`, `to` та `limit` у запит `GET /api/users/:_id/logs` для отримання частини журналу будь-якого користувача. `from` та `to` - дати у форматі `yyyy-mm-dd`. `limit` - це ціле число того, скільки журналів потрібно надіслати назад. ```js async (getUserInput) => { const url = getUserInput('url'); const res = await fetch(url + '/api/users', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `username=fcc_test_${Date.now()}`.substr(0, 29) }); if (res.ok) { const { _id, username } = await res.json(); const expected = { username, description: 'test', duration: 60, _id, date: new Date().toDateString() }; const addExerciseRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}&date=1990-01-01` }); const addExerciseTwoRes = await fetch(url + `/api/users/${_id}/exercises`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `description=${expected.description}&duration=${expected.duration}&date=1990-01-03` }); if (addExerciseRes.ok && addExerciseTwoRes.ok) { const logRes = await fetch( url + `/api/users/${_id}/logs?from=1989-12-31&to=1990-01-04` ); if (logRes.ok) { const { log } = await logRes.json(); assert.isArray(log); assert.equal(2, log.length); } else { throw new Error(`${logRes.status} ${logRes.statusText}`); } const limitRes = await fetch( url + `/api/users/${_id}/logs?limit=1` ); if (limitRes.ok) { const { log } = await limitRes.json(); assert.isArray(log); assert.equal(1, log.length); } else { throw new Error(`${limitRes.status} ${limitRes.statusText}`); } const filterDateBeforeLimitRes = await fetch( url + `/api/users/${_id}/logs?from=1990-01-02&to=1990-01-04&limit=1` ); if (filterDateBeforeLimitRes.ok) { const { log } = await filterDateBeforeLimitRes.json(); assert.isArray(log); assert.equal(1, log.length); } else { throw new Error(`${filterDateBeforeLimitRes.status} ${filterDateBeforeLimitRes.statusText}`); } } else { throw new Error(`${res.status} ${res.statusText}`); } } else { throw new Error(`${res.status} ${res.statusText}`); } }; ``` # --solutions-- ```js /** Backend challenges don't need solutions, because they would need to be tested against a full working project. Please check our contributing guidelines to learn more. */ ```