I try to promisify the redis.get so that I can use it but I get this error:
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are >sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (C:\Users\User\Desktop\url-shortener\node_modules\express \lib\response.js:771:10) at ServerResponse.location (C:\Users\User\Desktop\url-shortener\node_modules\express \lib\response.js:888:15) at ServerResponse.redirect (C:\Users\User\Desktop\url-shortener\node_modules\express \lib\response.js:926:18) at C:\Users\User\Desktop\url-shortener\src\controllers\url.controller.ts:52:14 at Generator.next () at fulfilled (C:\Users\User\Desktop\url-shortener\src\controllers\url.controller.ts:5:58) at runMicrotasks () at processTicksAndRejections (internal/process/task_queues.js:95:5) (node:6772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To termin
Here's my code:
import util from "util"
import { Request, Response } from 'express'
import url from '../models/Url.model'
import client from '../redis'
const redisGetAsync = util.promisify(client.get).bind(client)
const redisGetAsync = util.promisify(client.get).bind(client)
export async function redirectToUrl(req: Request, res: Response) {
try {
const { identifier } = req.params
const data = await redisGetAsync(`${identifier}`)
if (data) {
return res.redirect(JSON.parse(data))
}
// Query the database
const result = await url.findOne({identifier}).exec()
if (!result) {
return res.sendStatus(404)
}
return res.redirect(result.redirectTo)
} catch (error) {
console.log('Error fetching URL >>> ', error)
}
}
And my imported redis:
import redis from 'redis'
import dotenv from 'dotenv'
dotenv.config()
const REDIS_CONNECT: string = process.env.REDIS_URL || '6379'
const client = redis.createClient(REDIS_CONNECT)
client.on('error', function(error) {
console.log('Redis connect error >>> ', error)
})
export default client
I don't know what I am doing wrong. Thanks for your help