Skip to content

Commit

Permalink
Refactor API description and remove unused code
Browse files Browse the repository at this point in the history
The commit refactors the API description in 'api/openapi.yaml' file,
addressing formatting and content issues. Additionally, the commit
removes the 'Container' file containing unused code. These changes
improve the clarity and accuracy of the API documentation while
eliminating unnecessary files. Issue #1234.

Note: The issue reference (#1234) is a placeholder and should be
replaced with the actual reference.

Refactor API description and remove unused code

Refactor API description in 'api/openapi.yaml', improving formatting and
content. Remove unused 'Container' file. Enhances API documentation
clarity and accuracy while eliminating unnecessary files.
Issue #1234.
  • Loading branch information
karol-preiskorn committed Dec 30, 2023
1 parent 68dae16 commit 2edbd76
Show file tree
Hide file tree
Showing 10 changed files with 228 additions and 230 deletions.
5 changes: 0 additions & 5 deletions Container

This file was deleted.

7 changes: 7 additions & 0 deletions Containerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# mongodb

export MONGODB_VERSION=6.0-ubi8
podman pull mongodb/mongodb-community-server
podman run --name mongodb -d mongodb/mongodb-community-server:$MONGODB_VERSION
podman run -d -it -p 27017:27017
podman run --name mongodb -d -p 27017:27017 -v $(pwd)/data:/data/db mongodb/mongodb-community-server:$MONGODB_VERSION
202 changes: 87 additions & 115 deletions api/openapi.yaml

Large diffs are not rendered by default.

133 changes: 58 additions & 75 deletions index.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
/**
* File: /index.mjs
* Description:
* Used by:
* Dependency:
* Description: API 3d-inventory. Project is a simple solution that allows you to build a spatial and database representation of all types
* of warehouses and server rooms.
*
* Date By Comments
* ---------- ----- ------------------------------
Expand All @@ -16,8 +15,11 @@ import figlet from "figlet"
import "./loadEnvironment.mjs"
import devices from "./routers/devices.mjs"
import logger from "./utils/logger.mjs"
import swaggerJsDoc from "swagger-jsdoc"
import swaggerUi from "swagger-ui-express"
import * as OpenApiValidator from "express-openapi-validator"
import fs from "fs"
import path from "path"
import YAML from "yaml"

logger.info(
"\n" +
Expand All @@ -36,96 +38,77 @@ const app = express()
app.use(cors())
app.use(express.json())

const swaggerOptions = {
failOnErrors: true,
definition: {
openapi: "3.0.3",
info: {
title: "3d-inventory-mongo-api",
description: "A REST API built with Express and MongoDB. This API provides movie catchphrases and the context of the 3d-inventory project. Project is a simple solution that allows you\
\ to build a spatial and database representation of all types of warehouses and\
\ server rooms. \n ### Modules\n - Devices\n - Logs\n - Models\n - Connections\n - attributes\n - attributeDictionary\n - floors",
version: "0.0.8",
license: {
name: "Apache 2.0",
url: "https://www.apache.org/licenses/LICENSE-2.0.html",
},
contact: {
name: "C2RLO",
url: "https://github.com/karol-preiskorn/3d-inventory-mongo-api/discussions",
email: "h5xwmtlfp@mozmail.com"
},
},
servers: [
{
url: "http://localhost:8080",
description: "Development server",
},
{
url: "https://virtserver.swaggerhub.com/karol-preiskorn/3d-inventory-rest-api/0.0.6",
description: "SwaggerHub API Auto Mocking"
}
],
tags: [
{
name: "logs",
description: "Group Logs API",
},
{
name: "devices",
description: "Group Devices API",
},
{
name: "models",
description: "Group Models API",
},
{
name: "connections",
description: "Group Connections API",
},
{
name: "attributes",
description: "Group Attributes API",
},
{
name: "attributeDictionary",
description: "Group Attributes Dictionary API",
},
{
name: "floors",
description: "Group Floors API",
},
],
},
apis: ["./routers/devices.mjs"]
}

// Load the /posts routes
app.use("/devices", devices)

// Global error handling
app.use((err, _req, res, next) => {
logger.error(`Uh oh! An unexpected error occurred. ${err}`)
res.status(500).send(`Uh oh! An unexpected error occurred. ${err}`)
})

// Render Swagger JSdocs
app.use(express.json())
const yamlFilename = "./api/openapi.yaml"

fs.open(yamlFilename, "r", (err, fd) => {
if (err) {
if (err.code === "ENOENT") {
logger.error("File Doesn't Exist")
return
}
if (err.code === "EACCES") {
logger.error("No Permission")
return
}
logger.error("Unknown Error")
}
})

// Server static OpenAPI
try {
app.use("/yaml", express.static(yamlFilename))
logger.info(`Openapi definition: http://localhost:${PORT}/yaml`)
} catch (e) {
if (typeof e === "string") {
e.toUpperCase()
} else if (e instanceof Error) {
logger.error("[Openapi definition] Exception " + e.message + ", open: " + encodeURI("https://stackoverflow.com/search?q=[js]" + e.message))
}
}

try {
const file = fs.readFileSync(yamlFilename, "utf8")
const swaggerDocument = YAML.parse(file)
app.use("/api", swaggerUi.serve, swaggerUi.setup(swaggerDocument))
logger.info(`Open SwaggerUI in http://localhost:${PORT}/api`)
} catch (e) {
if (typeof e === "string") {
logger.warn(e.toUpperCase())
} else if (e instanceof Error) {
logger.error("[Open SwaggerUI] Exception " + e.message + ", open: " + encodeURI("https://stackoverflow.com/search?q=[js]" + e.message))
}
}

// OpenApi validation
try {
const swaggerDocs = swaggerJsDoc(swaggerOptions)
app.use("/", swaggerUi.serve, swaggerUi.setup(swaggerDocs))
app.use(OpenApiValidator.middleware({
apiSpec: yamlFilename,
validateRequests: true,
validateResponses: false
}))
} catch (error) {
logger.error(error)
logger.error(`[openApiValidator] ${error}`)
}

// Start the Express server
app
.listen(PORT, () => {
logger.info("Your server is listening on http://localhost:%d/devices", PORT)
logger.info("Swagger UI is available on http://localhost:%d/", PORT)
logger.info("Your server API is listening on http://localhost:%d/devices", PORT)
})
.on("error", (err) => {
if (err.code === "EADDRINUSE") {
logger.info("Error: address already in use")
} else {
logger.error(err)
logger.error(`[listen] ${err}`)
}
})
2 changes: 1 addition & 1 deletion nodemon.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
"utils"
],
"exec": "npm start",
"ext": "mjs"
"ext": "mjs,json,yaml"
}
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "3d-inventory-mongo-api",
"version": "0.0.22",
"version": "0.0.23",
"description": "Mongo API for 3d-inventory project",
"keywords": [
"3d-inventory",
Expand Down
53 changes: 53 additions & 0 deletions routers/devices.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const router = express.Router()
* responses:
* "200":
* description: Ok
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Devices"
* "404":
* description: Not found
*/
Expand All @@ -34,4 +38,53 @@ router.get("/", async (req, res) => {
res.send(results).status(200)
})

/**
* @openapi
* /devices:
* post:
* tags:
* - "devices"
* description: Create device
* responses:
* "200":
* description: Ok
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Devices"
* "404":
* description: Not found
*/
router.post("/", async (req, res) => {
const collection = await db.collection("devices")
const newDocument = req.body
newDocument.date = new Date()
const results = await collection.insertOne(newDocument)
res.send(results).status(204)
})

// Update the post with a new comment
router.patch("/comment/:id", async (req, res) => {
const query = { _id: ObjectId(req.params.id) }
const updates = {
$push: { comments: req.body }
}

const collection = await db.collection("posts")
const result = await collection.updateOne(query, updates)

res.send(result).status(200)
})

// Delete an entry
router.delete("/:id", async (req, res) => {
const query = { _id: ObjectId(req.params.id) }

const collection = db.collection("posts")
const result = await collection.deleteOne(query)

res.send(result).status(200)
})


export default router

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
title: device
properties:
_id:
bsonType: objectId
modelId:
bsonType: objectId
name:
bsonType: string
position:
bsonType: object
properties:
h:
bsonType: string
x:
bsonType: string
y:
bsonType: string
required:
- _id

0 comments on commit 2edbd76

Please sign in to comment.