Search code examples
node.jstinyurl

how i can create tinyURL with expiration date with node js


I'm generation tinyUrl and sending this via mail as well sms to customer ,i want to generate tinyURL from nodejs code so that if user access this URL after particular date then it should get expire . I can successfully generating tinyurl from bellow code but I want to generate link with expiry date so that Link will expire automatically once user click after particular date.

any way to solve this or is another alternative for this.

const tinyUrl = require('tinyurl')

const generateTinyUrl = function (mainUrl) {
  return new Promise((resolve, reject) => {
    tinyUrl.shorten(mainUrl).then((response) => {
      if (response !== 'error') {
        logger.info(util.format("Tiny URL Generated Properly."))
        resolve(response)
      } else {
        logger.error(util.format("Error while Generating the Tiny URL. Error: %j", response))
        reject(response)
      }
    }).catch((error) => {
      logger.error(util.format("Error while Generating the Tiny URL. Error: %j", error))
      reject(error)
    })
  })

Solution

  • From what I can gather, you're using the tinyurl npm package from https://www.npmjs.com/package/tinyurl which leverages the API from tinyurl.com to create shortened urls. This package doesn't support expiring links, which means that once you create a url using their service, it will be forever registered at tinyurl.com.

    You can, however, use the tinyurl API directly, ignoring the tinyurl npm package. Tinyurl has great documentation at tinyurl .com /app /dev (added spaces because link shorteners are blacklisted on SO) which explains that you can send a PATCH request to the api at /update to change where the link is sent.

    Since I can't see what is calling generateTinyUrl or how the response is used, I'm not sure what the best path forward is for your case. But, as I see it, you have two options.

    • Option 1: I would advise that you learn how to use an external API and remove the tinyurl npm package from your code. You could then schedule a cron job or similar to scan your urls, detect which ones have expired, and send a request to /update to change the url to a custom page that explains to the user that their link has expired.
    • Option 2: When you generate a tinyURL, have it point to a domain that you control. Generate that page so that when it is accessed, it gathers relevant data from your database, including its expiration date. When the expiration date is reached, that page could then display a custom expiration message which you write.