Skip to content

Commit

Permalink
refactor: common functions extracted from route.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
visrut-at-incubyte committed Sep 12, 2023
1 parent 7b224a6 commit ea9e5e1
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 69 deletions.
18 changes: 9 additions & 9 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const config = {
semi: false,
tabWidth: 2,
printWidth: 120,
singleQuote: true,
jsxSingleQuote: true,
trailingComma: 'none',
arrowParens: 'always',
endOfLine: 'auto',
semi: false,
tabWidth: 2,
printWidth: 120,
singleQuote: true,
jsxSingleQuote: true,
trailingComma: 'none',
arrowParens: 'always',
endOfLine: 'auto'
}

module.exports = config
module.exports = config
67 changes: 25 additions & 42 deletions app/create-survey/api/route.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,34 @@
import clientPromise from '@/app/mongodb';
import { NextResponse } from 'next/server';
import * as crypto from 'crypto';
import { v4 as uuidv4 } from "uuid";

function getClientIP(request: Request): string | undefined {
const headers = request.headers;
const xForwardedFor = headers.get('x-forwarded-for');

if (xForwardedFor) {
const ipList = xForwardedFor.split(',');
return ipList[0].trim();
} else {
if ((request as any).connection === undefined) {
return "undefined";
}
return (request as any).connection.remoteAddress;
}
}
import clientPromise from '@/app/mongodb'
import { NextResponse } from 'next/server'
import { v4 as uuidv4 } from 'uuid'
import { createHash, getClientIP } from '@/app/utils'

export async function POST(request: Request) {
const ip = getClientIP(request);
const sha256 = crypto.createHmac("sha256", process.env.SALT!);
const ipHash = sha256.update(ip!);
const ipHashDigest = ipHash.digest("hex");

const client = await clientPromise;
const db = client.db("survey-db");
const creatorHistory = await db.collection("creator-ip-hash").findOne({ ipHash: ipHashDigest });
const ip = getClientIP(request)
const hash = createHash(ip!)

const uuid = uuidv4();
const client = await clientPromise
const db = client.db('survey-db')
const creatorHistory = await db.collection('creator-ip-hash').findOne({ ipHash: hash })

if (creatorHistory === null) {
await db.collection("creator-ip-hash").insertOne({ ipHash: ipHashDigest, count: 1 });
} else {
const prevCount = creatorHistory.count;
const uuid = uuidv4()

if (prevCount >= 3) {
return NextResponse.json({ "error": "API Limit is reached" }, { status: 429 });
}
if (creatorHistory === null) {
await db.collection('creator-ip-hash').insertOne({ ipHash: hash, count: 1 })
} else {
const prevCount = creatorHistory.count

await db.collection("creator-ip-hash").updateOne({ ipHash: ipHashDigest }, { $set: { count: prevCount + 1 } });
if (prevCount >= 3) {
return NextResponse.json({ error: 'API Limit is reached' }, { status: 429 })
}

const survey = await request.json();
survey.creatorIpHash = ipHashDigest;
survey.uuid = uuid;
await db.collection("survey-templates").insertOne(survey);
await db.collection('creator-ip-hash').updateOne({ ipHash: hash }, { $set: { count: prevCount + 1 } })
}

return NextResponse.json({ "survey-id": uuid }, { status: 201 });
}
const survey = await request.json()
survey.creatorIpHash = hash
survey.uuid = uuid
await db.collection('survey-templates').insertOne(survey)

return NextResponse.json({ 'survey-id': uuid }, { status: 201 })
}
36 changes: 18 additions & 18 deletions app/mongodb.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import { MongoClient, ServerApiVersion } from 'mongodb'

const uri = process.env.MONGODB_URI;
const uri = process.env.MONGODB_URI

if (!uri) {
throw new Error('Please define the MONGODB_URI environment variable inside .env.local')
throw new Error('Please define the MONGODB_URI environment variable inside .env.local')
}

let client: MongoClient;
let clientPromise: Promise<MongoClient>;
let client: MongoClient
let clientPromise: Promise<MongoClient>

const options = {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true
}
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true
}
}

declare global {
var _mongoClientPromise: Promise<MongoClient>;
var _mongoClientPromise: Promise<MongoClient>
}

if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise
} else {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
clientPromise = client.connect()
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}

export default clientPromise;
export default clientPromise
23 changes: 23 additions & 0 deletions app/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as crypto from 'crypto'

export function getClientIP(request: Request): string | undefined {
const headers = request.headers
const xForwardedFor = headers.get('x-forwarded-for')

if (xForwardedFor) {
const ipList = xForwardedFor.split(',')
return ipList[0].trim()
} else {
if ((request as any).connection === undefined) {
return 'undefined'
}
return (request as any).connection.remoteAddress
}
}

export function createHash(data: string): string {
const sha256 = crypto.createHmac('sha256', process.env.SALT!)
const ipHash = sha256.update(data!)
const ipHashDigest = ipHash.digest('hex')
return ipHashDigest
}

0 comments on commit ea9e5e1

Please sign in to comment.