Last active
May 24, 2020 19:13
-
-
Save J3698/e47d7e0ec83b01012e3ca8448daf98dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Create a shortening and return the shorturl if successful. Returns null if | |
* the shorturl already exists and is not the requested shortening, or if the | |
* longurl already has a random shortening and this shortening is also random. | |
* | |
* May throw other db errors. | |
*/ | |
const addShortening = async (shortUrl, longUrl, isRandom) => { | |
let addShorteningQuery = 'INSERT INTO shortenings (shorturl, longurl, israndom) VALUES ($1, $2, $3)'; | |
try { | |
await pool.query(addShorteningQuery, [shortUrl, longUrl, isRandom]); | |
return shortUrl; | |
} catch (e) { | |
if (e.constraint === 'shortenings_pkey') { | |
// shortUrl is in the database, this is only okay if the longurl is identical | |
return (await getLongUrl(shortUrl)) === longUrl ? shortUrl : null; | |
} else if (e.constraint === 'random_shortening_constraint') { | |
// can't add two random urls for one longurl | |
return null; | |
} | |
// some other error | |
throw e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment