This project provides a RESTful API for tracking sleep records. Users can add, retrieve, and delete sleep records.
- Node.js (v14.x or later)
- MongoDB (local or cloud instance)
-
Clone the repository:
git clone https://github.com/yourusername/sleep-tracker-api.git cd sleep-tracker-api
-
Install dependencies:
npm install
-
Set up environment variables:
Create a
.env
file in the root directory and add the following variables:PORT=3000 MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.qjn3mju.mongodb.net/storeDB
Replace
mongodb+srv://<username>:<password>@cluster0.qjn3mju.mongodb.net/storeDB
with your MongoDB connection string.
-
Start the server:
npm start
-
The server will start on
http://localhost:3000
.
You can access the live version of the API at: Sleep Tracker API
-
URL:
/sleep
-
Method:
POST
-
Request Body:
{ "userId": "user123", "hours": 7, "timestamp": "2023-05-20T00:00:00.000Z" }
-
Success Response:
{ "_id": "60c72b2f9b1d4f0015a4b5c2", "userId": "user123", "hours": 7, "timestamp": "2023-05-20T00:00:00.000Z", "__v": 0 }
-
Error Responses:
-
Missing fields:
{ "message": "userId, hours, and timestamp are required fields" }
-
Invalid hours:
{ "message": "hours must be a valid positive number and in the range 1-24" }
-
Invalid timestamp:
{ "message": "timestamp must be a valid date" }
-
Record already exists:
{ "message": "Record already exists" }
-
-
URL:
/sleep/:userId
-
Method:
GET
-
URL Parameters:
userId
: The ID of the user whose sleep records you want to retrieve.
-
Success Response:
[ { "_id": "60c72b2f9b1d4f0015a4b5c2", "userId": "user123", "hours": 7, "timestamp": "2023-05-20T00:00:00.000Z", "__v": 0 }, { "_id": "60c72b3f9b1d4f0015a4b5c3", "userId": "user123", "hours": 8, "timestamp": "2023-05-21T00:00:00.000Z", "__v": 0 } ]
-
Error Response:
{ "message": "No records found for the specified userId" }
-
URL:
/sleep/:recordId
-
Method:
DELETE
-
URL Parameters:
recordId
: The ID of the sleep record to delete.
-
Success Response:
{ "message": "Record has been deleted" }
-
Error Response:
{ "message": "No record found, Cannot be deleted" }
To run the tests for the API endpoints:
-
Ensure your MongoDB instance is running.
-
Run the tests:
npm test
The tests will validate the functionality of the API endpoints.