Skip to content

Commit

Permalink
Public apis merge request 1 (hiteshchoudhary#1)
Browse files Browse the repository at this point in the history
* Initial setup
- Add dockerfile
- Add docker compose yml file
- Add healthcheck endpoint
- Configure mongoose + mongodb
- Add error middleware to catch errors at the central place
- Add request handler async wrapper

* - Add random users public api endpoints
- Fix typos
- Fix error middleware variable bug
- Add random users json

* - Add random products public api
- Add get user by id endpoint in random user
- Change radom user json file structure

* Add random joke endpoints and controllers

* - Add query based search functionality in public apis
- Add query to include only comma separated fields in the response"

* Update README.md

* Add books JSON and api endpoints in public api section

* Add quotes json and endpoints in public apis

* Add pagination utility function for all the controllers

* Add meals json and endpoints
  • Loading branch information
wajeshubham authored May 25, 2023
1 parent 4e5a8b5 commit a51a32a
Show file tree
Hide file tree
Showing 36 changed files with 73,509 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/.vscode
/node_modules
3 changes: 3 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=8080
MONGODB_URI=mongodb://mongodb:27017/apihub
NODE_ENV=development
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# Logs
logs

/tmp
/.vscode
18 changes: 18 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM node:alpine

RUN mkdir -p /usr/src/apihub && chown -R node:node /usr/src/apihub

WORKDIR /usr/src/apihub

# Copy package json and yarn lock only to optimise the image building
COPY package.json yarn.lock ./

USER node

RUN yarn install --pure-lockfile

COPY --chown=node:node . .

EXPOSE 8080

CMD [ "npm", "start" ]
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
# apihub
A API learning go
# 🧊 ApiHub

All apis you need in a single place!

# Setup

Create `.env` file in the root folder and copy paste the content of `.env.sample` as it is

Install Docker on your machine and run the following command inside the root folder.

```
docker-compose up --build
```
25 changes: 25 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
version: '3.8'

services:
backend:
image: apihub-server
build: .
ports:
- 8080:8080
volumes:
- ./:/usr/src/apihub
- /usr/src/apihub/node_modules
env_file:
- ./.env
depends_on:
- mongodb
mongodb:
image: mongo
container_name: mongodb
volumes:
- data:/data/db
ports:
- 27017:27017

volumes:
data:
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "apihub",
"version": "1.0.0",
"description": "A API learning go",
"type": "module",
"main": "src/index.js",
"scripts": {
"start": "nodemon index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/hiteshchoudhary/apihub.git"
},
"keywords": [
"apihub"
],
"author": "Hitesh Choudhary",
"license": "ISC",
"bugs": {
"url": "https://github.com/hiteshchoudhary/apihub/issues"
},
"homepage": "https://github.com/hiteshchoudhary/apihub#readme",
"dependencies": {
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"mongoose": "^7.2.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
42 changes: 42 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import cors from "cors";
import dotenv from "dotenv";
import express from "express";

dotenv.config({
path: "./.env",
});

const app = express();

// global middlewares
app.use(
cors({
origin: "*",
credentials: true,
})
);
app.use(express.json({ limit: "16kb" }));
app.use(express.urlencoded({ extended: true, limit: "16kb" }));

// api routes
import { errorHandler } from "./middlewares/error.middlewares.js";
import healthcheckRouter from "./routes/healthcheck.routes.js";
import randomuserRouter from "./routes/public/randomuser.routes.js";
import randomproductRouter from "./routes/public/randomproduct.routes.js";
import randomjokeRouter from "./routes/public/randomjoke.routes.js";
import bookRouter from "./routes/public/book.routes.js";
import quoteRouter from "./routes/public/quote.routes.js";
import mealRouter from "./routes/public/meal.routes.js";

app.use("/api/v1/healthcheck", healthcheckRouter);
app.use("/api/v1/public/randomusers", randomuserRouter);
app.use("/api/v1/public/randomproducts", randomproductRouter);
app.use("/api/v1/public/randomjokes", randomjokeRouter);
app.use("/api/v1/public/books", bookRouter);
app.use("/api/v1/public/quotes", quoteRouter);
app.use("/api/v1/public/meals", mealRouter);

// common error handling middleware
app.use(errorHandler);

export { app };
10 changes: 10 additions & 0 deletions src/controllers/healthcheck.controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ApiResponse } from "../utils/ApiResponse.js";
import { asyncHandler } from "../utils/asyncHandler.js";

const healthcheck = asyncHandler(async (req, res) => {
return res
.status(200)
.json(new ApiResponse(200, "OK", "Health check passed"));
});

export { healthcheck };
66 changes: 66 additions & 0 deletions src/controllers/public/book.controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import booksJson from "../../json/books.json" assert { type: "json" };
import { filterObjectKeys, getPaginatedPayload } from "../../utils/index.js";
import { ApiError } from "../../utils/ApiError.js";
import { ApiResponse } from "../../utils/ApiResponse.js";
import { asyncHandler } from "../../utils/asyncHandler.js";

const getBooks = asyncHandler(async (req, res) => {
const page = +(req.query.page || 1);
const limit = +(req.query.limit || 10);
const query = req.query.query?.toLowerCase(); // search query
const inc = req.query.inc?.split(","); // only include fields mentioned in this query

const allBooks = booksJson;

const startPosition = +(page - 1) * limit;

let booksArray = (
query
? [...booksJson].filter((book) => {
return (
book.searchInfo?.textSnippet.toLowerCase().includes(query) ||
book.volumeInfo.title?.includes(query) ||
book.volumeInfo.subtitle?.includes(query)
);
})
: [...booksJson]
).slice(startPosition, startPosition + limit);

if (inc && inc[0]?.trim()) {
booksArray = filterObjectKeys(inc, booksArray);
}

return res
.status(200)
.json(
new ApiResponse(
200,
getPaginatedPayload(booksArray, allBooks.length, req, page, limit),
"Books fetched successfully"
)
);
});

const getBookById = asyncHandler(async (req, res) => {
const { bookId } = req.params;
const book = booksJson.find((book) => +book.id === +bookId);
if (!book) {
throw new ApiError(404, "Book does not exist.");
}
return res
.status(200)
.json(new ApiResponse(200, book, "Book fetched successfully"));
});

const getARandomBook = asyncHandler(async (req, res) => {
const booksArray = booksJson;
const randomIndex = Math.floor(Math.random() * booksArray.length);

return res
.status(200)
.json(
new ApiResponse(200, booksArray[randomIndex], "Book fetched successfully")
);
});

export { getBooks, getARandomBook, getBookById };
Loading

0 comments on commit a51a32a

Please sign in to comment.