Skip to content

Commit

Permalink
Merge pull request 100xdevs-cohort-2#866 from Sainith123/week-12
Browse files Browse the repository at this point in the history
week 12
  • Loading branch information
hkirat authored Mar 4, 2024
2 parents 364f8fc + 4429657 commit 596afec
Show file tree
Hide file tree
Showing 10 changed files with 348 additions and 0 deletions.
179 changes: 179 additions & 0 deletions week-12/12.1 Relations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# Survey Poll App

Create a basic Survey/Poll application built with Node.js and Prisma.

## Overview

The application allows users to create and participate in surveys. Each survey consists of one or more questions, and each question can have multiple options. Users can select an option to vote in a survey.


## Features

- Create a new survey
- Get a list of all surveys
- Get details of a specific survey
- Vote in a survey
- Get the results of a survey


## Prerequisites

Before you begin, ensure you have met the following requirements:

- You have installed Node.js and npm.
- You have installed Prisma CLI.
- You have a PostgreSQL database setup.


## API Endpoints

The application provides the following endpoints:

- `GET /surveys`: Fetch all surveys.
- `POST /surveys`: Create a new survey.
- `GET /surveys/:id`: Fetch a specific survey.
- `PUT /surveys/:id`: Update a specific survey.
- `DELETE /surveys/:id`: Delete a specific survey.


## Tech Stack

- Node.js: JavaScript runtime
- Express.js: Web application framework
- Prisma: Next-generation Node.js and TypeScript ORM
- Jest: JavaScript testing framework

## Getting Started

Please follow the standard instructions to initiate a node app


- Clone the repo


1.Change your directory
```
cd survey-poll-app
```

2.Initiate a node app
```
npm init -y
```

3.Install dependencies
```
npm install express prisma
```

4. Create Prisma schema file(you can directly paste the provided schema into it.make sure to provide db url)
```
npx prisma init
```

5. Configure Database Connection
In the schema.prisma file, update env("DATABASE_URL") with your actual PostgreSQL database connection URL.

6. Generate Prisma Client
```
npx prisma generate
```
Now you can use prisma client in your code

7. Apply migrations
```
npx prisma migrate dev --name <name for you migration>
```

8. Create an Express App

9. Implement CRUD Operations

Start Coding!!!

<br>

## Directory Structure

**NOTE:Please try to adhere to the below directory structure, follow the same naming convention for files and directories in your app, this is a good practice to create applications(Again that's optional)**

- Clone the repo and write your code inside `survey-poll-app`


```
survey-poll-app/
|-- node_modules/
|-- prisma/
| |-- schema.prisma
|-- src/
| |-- controllers/
| | |-- surveyController.js
| |
| |-- models/
| | |-- surveyModel.js
| |
| |-- routes/
| | |-- surveyRoutes.js
| |
| |-- config.js
| |-- server.js
|-- package.json
|-- .env
```
<br><br>

## Prisma Schema for your Reference

**Note : Not mandatory to follow this. this is just for your reference**

Just try to follow this basic structure for creating a survey

![img](./basic-survey.png)


<br>

<b>Click here to view schema<b>

<details>

<summary><b>Please try to make your own schema. Use this only if you are unable to make your own one<b></summary>

```
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Survey {
id Int @id @default(autoincrement())
title String
questions Question[]
}
model Question {
id Int @id @default(autoincrement())
text String
options Option[]
surveyId Int
Survey Survey @relation(fields: [surveyId], references: [id])
}
model Option {
id Int @id @default(autoincrement())
text String
votes Int @default(0)
questionId Int
Question Question @relation(fields: [questionId], references: [id])
}
```
</details>




Binary file added week-12/12.1 Relations/basic-survey.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions week-12/12.1 Relations/solution/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
PORT=3000
SECRET_KEY="your-secret-key"
25 changes: 25 additions & 0 deletions week-12/12.1 Relations/solution/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "survey-poll-app",
"version": "1.0.0",
"description": "A basic survey/poll app built with Node.js and Prisma",
"main": "src/server.js",
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"test": "jest"
},
"keywords": ["survey", "poll", "nodejs", "prisma"],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"@prisma/client": "^2.30.0",
"dotenv": "^10.0.0"
},
"devDependencies": {
"jest": "^27.2.0",
"nodemon": "^2.0.12",
"@prisma/cli": "^2.30.0",
"supertest": "^6.1.3"
}
}
30 changes: 30 additions & 0 deletions week-12/12.1 Relations/solution/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Survey {
id Int @id @default(autoincrement())
title String
questions Question[]
}

model Question {
id Int @id @default(autoincrement())
text String
options Option[]
surveyId Int
Survey Survey @relation(fields: [surveyId], references: [id])
}

model Option {
id Int @id @default(autoincrement())
text String
votes Int @default(0)
questionId Int
Question Question @relation(fields: [questionId], references: [id])
}
6 changes: 6 additions & 0 deletions week-12/12.1 Relations/solution/src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
port: process.env.PORT || 3000,
db: {
url: process.env.DATABASE_URL,
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const SurveyModel = require('../models/surveyModel');

class SurveyController {
async getAllSurveys(req, res) {
try {
const surveys = await SurveyModel.find();
res.status(200).json(surveys);
} catch (error) {
res.status(500).json({ message: error.message });
}
}

async getSurveyById(req, res) {
try {
const survey = await SurveyModel.findById(req.params.id);
if (survey == null) {
return res.status(404).json({ message: 'Survey not found' });
}
res.status(200).json(survey);
} catch (error) {
res.status(500).json({ message: error.message });
}
}

async createSurvey(req, res) {
const survey = new SurveyModel(req.body);
try {
const newSurvey = await survey.save();
res.status(201).json(newSurvey);
} catch (error) {
res.status(400).json({ message: error.message });
}
}

async updateSurvey(req, res) {
try {
const updatedSurvey = await SurveyModel.updateOne({ _id: req.params.id }, req.body);
res.status(200).json(updatedSurvey);
} catch (error) {
res.status(400).json({ message: error.message });
}
}

async deleteSurvey(req, res) {
try {
await SurveyModel.deleteOne({ _id: req.params.id });
res.status(200).json({ message: 'Survey deleted' });
} catch (error) {
res.status(500).json({ message: error.message });
}
}
}

module.exports = new SurveyController();
26 changes: 26 additions & 0 deletions week-12/12.1 Relations/solution/src/models/surveyModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

class SurveyModel {
static async getAllSurveys() {
return await prisma.survey.findMany();
}

static async getSurveyById(id) {
return await prisma.survey.findUnique({ where: { id } });
}

static async createSurvey(data) {
return await prisma.survey.create({ data });
}

static async updateSurvey(id, data) {
return await prisma.survey.update({ where: { id }, data });
}

static async deleteSurvey(id) {
return await prisma.survey.delete({ where: { id } });
}
}

module.exports = SurveyModel;
13 changes: 13 additions & 0 deletions week-12/12.1 Relations/solution/src/routes/surveyRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const express = require('express');
const SurveyController = require('../controllers/surveyController');

const router = express.Router();
const surveyController = new SurveyController();

router.get('/', surveyController.getAllSurveys);
router.get('/:id', surveyController.getSurveyById);
router.post('/', surveyController.createSurvey);
router.put('/:id', surveyController.updateSurvey);
router.delete('/:id', surveyController.deleteSurvey);

module.exports = router;
12 changes: 12 additions & 0 deletions week-12/12.1 Relations/solution/src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const express = require('express');
const surveyRoutes = require('./routes/surveyRoutes');
const config = require('./config');

const app = express();

app.use(express.json());
app.use('/api/surveys', surveyRoutes);

app.listen(config.port, () => {
console.log(`Server is running on port ${config.port}`);
});

0 comments on commit 596afec

Please sign in to comment.