Skip to content

Commit

Permalink
Merge pull request #71 from mudroljub/develop
Browse files Browse the repository at this point in the history
docs + develop
  • Loading branch information
mudroljub authored Nov 23, 2024
2 parents c34948b + 5bf4424 commit 9c29ef5
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 40 deletions.
18 changes: 7 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ Github repo: [github.com/mudroljub/programming-quotes-api](https://github.com/mu

### Public Routes

#### GET `/quotes/random`
#### GET [`/quotes/random`](/quotes/random)
- **Description**: Fetches a random programming quote.

#### GET `/quotes`
- **Description**: Retrieves all programming quotes.

#### GET `/quotes?page=1&quotesPerPage=20`
- **Description**: Retrieves quotes with optional query parameters:
#### GET [`/quotes?author=Edsger_W._Dijkstra`](/quotes?author=Edsger_W._Dijkstra)
#### GET [`/quotes?page=1&quotesPerPage=20`](/quotes?page=1&quotesPerPage=20)
#### GET [`/quotes`](/quotes)
- **Description**: Retrieves quotes, with optional query parameters:
- `page`: The page number (default: 1).
- `quotesPerPage`: Number of quotes per page (default: 20).
- `author`: Filter quotes by a specific author.
Expand Down Expand Up @@ -89,11 +88,8 @@ mongoimport --db quotes --collection quotes --file quotes.json --jsonArray --use
Create `.env` file proper values:

```
# Database credentials (obtain from MongoDB)
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_DOMAIN=
# database credentials (obtain from MongoDB)
CONNECTION_STRING=
# whatever random string you like
JWT_SECRET=
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"repository": "https://github.com/mudroljub/programming-quotes-api",
"main": "src/app.js",
"scripts": {
"save": "wget https://programming-quotes-api.herokuapp.com/quotes/ -O backup/quotes.json",
"save": "wget https://programming-quotes-api.azurewebsites.net/quotes/ -O backup/quotes.json",
"start": "node src/app.js",
"dev": "nodemon src/app.js",
"lint": "eslint . --fix"
Expand Down
23 changes: 9 additions & 14 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,33 @@
import 'dotenv/config.js'
import fs from 'fs'
import { promises as fs } from 'fs'
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import { marked } from 'marked'
import compression from 'compression'
import { promisify } from 'util'

import { mongoUri } from './config/db.js'
import { port, domain } from './config/host.js'
import router from './routes/router.js'
import { normalizeRequestBody } from './middleware/normalize.js'
import { normalizeJsonKeys } from './middleware/normalize.js'

const app = express()
const readFileAsync = promisify(fs.readFile)

// CONFIG
// MIDDLEWARES
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(normalizeRequestBody)
app.use(compression())
app.use(normalizeJsonKeys)

mongoose.connect(mongoUri)
.catch(err => console.error('MongoDB connection error:', err))
mongoose.connect(process.env.CONNECTION_STRING)
.catch(err => console.error('Could not connect to database:', err))

// ROUTES
app.get('/', async(req, res) => {
try {
const file = await readFileAsync('README.md', 'utf8')
res.send(marked(file.toString()))
const data = await fs.readFile('README.md', 'utf8')
res.send(marked(data))
} catch (err) {
res.status(500).send('Error reading file')
res.status(500).send(`Error reading file: ${err.message}`)
}
})

Expand Down
5 changes: 0 additions & 5 deletions src/config/db.js

This file was deleted.

2 changes: 1 addition & 1 deletion src/config/host.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const port = process.env.PORT || 5000

const domain = process.env.NODE_ENV === 'development'
? `http://localhost:${port}`
: 'https://programming-quotes-api.herokuapp.com'
: 'https://programming-quotes-api.azurewebsites.net'

export {
port,
Expand Down
12 changes: 8 additions & 4 deletions src/middleware/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@ const normalizeKeys = obj => {
if (typeof obj !== 'object' || obj === null) return obj

return Object.keys(obj).reduce((acc, key) => {
// spusti samo prvo slovo ključa
// spušta prvo slovo
const lowerCaseKey = key.charAt(0).toLowerCase() + key.slice(1)
acc[lowerCaseKey] = normalizeKeys(obj[key])
return acc
}, {})
}

export const normalizeRequestBody = (req, res, next) => {
export const normalizeJsonKeys = (req, res, next) => {
if (req.body)
req.body = normalizeKeys(req.body)

next()
}

export default normalizeRequestBody
export function normalizeQueryParams(req, res, next) {
if (req.query.author)
req.query.author = req.query.author.replace(/_/g, ' ')

next()
}
10 changes: 6 additions & 4 deletions src/routes/quotesRouter.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { Router } from 'express'
import compression from 'compression'

import QuoteController from '../controllers/QuoteController.js'
import { authenticate, authorizeUser, authorizeEditor } from '../middleware/auth.js'
import { normalizeQueryParams } from '../middleware/normalize.js'

const router = new Router()

// special routes
// preceding routes
router.get('/random', QuoteController.random)
router.post('/vote', authenticate, QuoteController.vote)

router.get('/', QuoteController.getQuotes) // query params: page, quotesPerPage, author
// query params: page, quotesPerPage, author
router.get('/', normalizeQueryParams, compression(), QuoteController.getQuotes)
router.get('/:id', QuoteController.getById)

router.post('/', authorizeUser, QuoteController.create)
router.put('/:id', authorizeEditor, QuoteController.update)

router.delete('/:id', QuoteController.delete)

export default router

0 comments on commit 9c29ef5

Please sign in to comment.