Skip to content

Commit

Permalink
add express validator
Browse files Browse the repository at this point in the history
  • Loading branch information
felipepasc committed Jul 21, 2024
1 parent 1377db0 commit ec64236
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
13 changes: 13 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-validator": "^7.1.0",
"node-cron": "^3.0.3",
"sequelize": "^6.37.3",
"sqlite3": "^5.1.7",
Expand Down
31 changes: 28 additions & 3 deletions source/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const express = require("express");
const { body, param, query, validationResult } = require("express-validator");
const router = express.Router();
const { v4: uuidv4 } = require("uuid");
const ShortURL = require("../models/ShortURLModel");
Expand Down Expand Up @@ -73,7 +74,16 @@ const apiKeys = process.env.API_KEYS.split(",");
* 500:
* description: Failed to create short URL
*/
router.post("/", async (req, res) => {
router.post("/", [
body("url").isURL().withMessage("Invalid URL format"),
body("key").isString().withMessage("API key is required"),
body("expiration").optional().isISO8601().withMessage("Invalid expiration date format")
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const { url, key, expiration } = req.body;

if (!apiKeys.includes(key)) {
Expand Down Expand Up @@ -127,7 +137,15 @@ router.post("/", async (req, res) => {
* 500:
* description: Failed to delete URL
*/
router.delete("/:id", async (req, res) => {
router.delete("/:id", [
param("id").isUUID().withMessage("Invalid URL ID format"),
query("key").isString().withMessage("API key is required")
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const id = req.params.id;
const key = req.query.key;

Expand Down Expand Up @@ -202,7 +220,14 @@ router.get("/", async (req, res) => {
* 500:
* description: Failed to retrieve URL
*/
router.get("/:id", async (req, res) => {
router.get("/:id", [
param("id").isUUID().withMessage("Invalid URL ID format")
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const id = req.params.id;

try {
Expand Down

0 comments on commit ec64236

Please sign in to comment.