Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): Add deletePlan controller, tests, and CI pipeline #2

Merged
merged 2 commits into from
Sep 30, 2023
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
HOSTNAME=xxxxxxxxx
PORT=xxxx
REDIS_PORT=xxxx
2 changes: 1 addition & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ module.exports = {
'default-param-last': 'off',
camelcase: 'off',
},
};
}
35 changes: 35 additions & 0 deletions .github/workflows/test-suite.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Unit Test Suite

# Controls when the action will run.
on:
workflow_dispatch:
# Triggers the workflow on push or pull request events but only for the master branch
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-latest
environment: ${{ vars.ENVIRONMENT }}
strategy:
matrix:
node-version: [18.x]

name: Run unit tests
steps:
- uses: actions/checkout@v4
- name: "Create .env file"
run: |
touch .env
echo HOSTNAME=${{ vars.HOSTNAME }} >> .env
echo PORT=${{ vars.PORT }} >> .env
echo DATABASE=${{ vars.REDIS_PORT }} >> .env
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: yarn
- run: yarn test
2 changes: 1 addition & 1 deletion .prettierrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ module.exports = {
printWidth: 80,
tabWidth: 2,
endOfLine: 'auto',
};
}
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2023 Siddharth Rawat

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
# CSYE 7255: Adv Big Data Indexing Techniques
# INFO-7255: Adv Big Data Indexing Techniques

>NOTE: This is a WIP. Please visit different branches for each version of the demos for the submissions
[![Unit Test Suite](https://github.com/sydrawat01/INFO7255/actions/workflows/test-suite.yml/badge.svg)](https://github.com/sydrawat01/INFO7255/actions/workflows/test-suite.yml)

## Setup

1. Install the dependencies

```shell
yarn
#or if you are using npm: npm i
```
```shell
yarn
# or if you are using npm: npm i
```

2. Start the server locally

```shell
yarn start:dev
# npm run start:dev
```
```shell
yarn start:dev
# npm run start:dev
```

## Author

Expand Down
18 changes: 14 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
{
"name": "api",
"version": "1.1.0",
"version": "1.2.0",
"description": "RESTful API",
"main": "src/server.js",
"author": "Siddharth Rawat <[email protected]>",
"license": "MIT",
"scripts": {
"env": "nodemon -r dotenv/config",
"start:dev": "nodemon --exec babel-node ./src/server.js",
"clean": "rm -rf ./dist"
"clean": "rm -rf ./dist",
"build": "yarn clean && babel ./src/server.js --out-dir ./dist",
"test": "mocha --require @babel/register './tests/*.test.js' --recursive --exit",
"test:dev": "mocha --require @babel/register './tests/*.test.js' --watch"
},
"dependencies": {
"ajv": "^8.12.0",
"app-root-path": "^3.1.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
Expand All @@ -27,6 +29,14 @@
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/preset-env": "^7.22.15",
"@babel/register": "^7.22.15",
"nodemon": "^3.0.1"
"eslint": "^8.50.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-prettier": "^5.0.0",
"mocha": "^10.2.0",
"nodemon": "^3.0.1",
"prettier": "^3.0.3",
"supertest": "^6.3.3"
}
}
2 changes: 0 additions & 2 deletions src/api/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import express from 'express'
import { errorHandler } from './middlewares/errorHandler'
// import { healthRoute } from './routes/health.route'
// import { planRoute } from './routes/plan.route'
import { healthRoute, planRoute } from './routes/index.routes'

const app = express()
Expand Down
1 change: 0 additions & 1 deletion src/api/controllers/health.controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logger from '../../configs/logger.config'
// import appConfig from '../configs/app.config'

const health = (req, res) => {
const { protocol, method, hostname, originalUrl } = req
Expand Down
58 changes: 49 additions & 9 deletions src/api/controllers/plan.controller.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { findPlan, addPlan, delPlan } from '../services/redis.client'
import { findPlan, addPlan, deleteByPlanId } from '../services/redis.client'
import { validate, md5hash } from '../utils/schemaValidation'
import {
BadRequestError,
InternalServerError,
ResourceNotFoundError,
PreConditionFailedError,
conflictHandler,
createHandler,
noContentHandler,
notModifiedHandler,
successHandler,
} from '../utils/error.util'
Expand All @@ -18,32 +21,31 @@ const getPlan = async (req, res, next) => {
`Requesting ${method} ${protocol}://${hostname}${originalUrl}`,
metaData
)
const planId = params.planId
try {
const { planId } = params
if (planId === null || planId === '' || planId === '{}') {
throw new BadRequestError(`Invalid planId`)
}
const value = await findPlan(planId)
if (value.objectId === planId) {
// conditional read based on `if-none-match` header
if (
req.headers['if-none-match'] &&
value.ETag == req.headers['if-none-match']
value.ETag === req.headers['if-none-match']
) {
res.setHeader('ETag', value.ETag)
const data = {
message: 'Plan has not changed',
plan: JSON.parse(value.plan),
}
notModifiedHandler(res, data)
return
} else {
res.setHeader('ETag', value.ETag)
const data = {
message: 'Plan has changed',
plan: JSON.parse(value.plan),
}
successHandler(res, data)
return
}
} else {
throw new ResourceNotFoundError(`Plan not found`)
Expand All @@ -64,20 +66,20 @@ const savePlan = async (req, res, next) => {
try {
if (validate(req.body)) {
const value = await findPlan(req.body.objectId)
logger.warn(`VALUE: ${value}`)
if (value) {
res.setHeader('ETag', value.ETag)
const data = { message: 'Item already exists' }
conflictHandler(res, data)
return
} else {
const ETag = (await addPlan(req.body)).ETag
const newPlan = await addPlan(req.body)
const { ETag } = newPlan
res.setHeader('ETag', ETag)
const data = {
message: 'Item added',
ETag,
}
createHandler(res, data)
return
}
} else {
throw new BadRequestError(`Item is not valid`)
Expand All @@ -87,6 +89,44 @@ const savePlan = async (req, res, next) => {
}
}

const deletePlan = async (req, res, next) => {}
const deletePlan = async (req, res, next) => {
const { protocol, method, hostname, originalUrl, params } = req
const headers = { ...req.headers }
const metaData = { protocol, method, hostname, originalUrl, headers, params }
logger.info(
`Requesting ${method} ${protocol}://${hostname}${originalUrl}`,
metaData
)
try {
const { planId } = params
if (planId === null || planId === '' || planId === '{}') {
throw new BadRequestError(`Invalid planId`)
}
const value = await findPlan(planId)
if (value.objectId === planId) {
// conditional delete based on `if-match` header
if (req.headers['if-match'] && value.ETag === req.headers['if-match']) {
const data = {
plan: JSON.parse(value.plan),
}
logger.info(`Item found`, JSON.parse(value.plan))
if (deleteByPlanId(planId)) {
logger.info(`Item deleted`, JSON.parse(value.plan))
noContentHandler(res, data)
} else {
throw new InternalServerError(`Item not deleted`)
}
} else {
throw new PreConditionFailedError(
`ETag provided in header is not valid`
)
}
} else {
throw new ResourceNotFoundError(`Plan not found`)
}
} catch (err) {
next(err)
}
}

export { getPlan, savePlan, deletePlan }
5 changes: 3 additions & 2 deletions src/api/middlewares/errorHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import logger from '../../configs/logger.config'
export const errorHandler = (err, req, res, next) => {
const errStatus = err.statusCode || 500
const errMessage = err.message || 'Something went wrong'
res.status(errStatus).json({
const meta = {
error: err.name,
message: errMessage,
data: err.data,
// stack: err.stack,
})
}
res.status(errStatus).json(meta)
logger.error(errMessage, meta)
}
2 changes: 1 addition & 1 deletion src/api/routes/health.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ const router = express.Router()
router.get('/', health)
router.get('/health', health)

export {router as healthRoute }
export { router as healthRoute }
4 changes: 2 additions & 2 deletions src/api/routes/plan.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { savePlan, getPlan, deletePlan } from '../controllers/plan.controller'
const router = express.Router()

router.post('/plan', savePlan)
router.get('/plan/:id', getPlan)
router.delete('/plan', deletePlan)
router.get('/plan/:planId', getPlan)
router.delete('/plan/:planId', deletePlan)

export { router as planRoute }
17 changes: 11 additions & 6 deletions src/api/services/redis.client.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'dotenv/config'
import { createClient } from 'redis'
import md5 from 'md5'
import appConfig from '../../configs/app.config'
import logger from '../../configs/logger.config'
import md5 from 'md5'

const { REDIS_PORT } = appConfig

Expand All @@ -19,19 +19,24 @@ const findPlan = async (key) => {
const value = await client.hGetAll(key)
if (value.objectId === key) {
return value
} else {
return false
}
return false
}

const addPlan = async (body) => {
const ETag = md5(body)
await client.hSet(body.objectId, 'plan', JSON.stringify(body))
await client.hSet(body.objectId, 'ETag', ETag)
await client.hSet(body.objectId, 'objectId', body.objectId)
return await this.findPlan(body.objectId)
const newPlan = await findPlan(body.objectId)
return newPlan
}

const delPlan = async () => {}
const deleteByPlanId = async (planId) => {
if (await client.del(planId)) {
return true
}
return false
}

export { findPlan, addPlan, delPlan }
export { findPlan, addPlan, deleteByPlanId }
Loading