Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prototype custom URL shortener sample #1100

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions Node/custom-url-shortener/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log*
firebase-debug.*.log*

# Firebase cache
.firebase/

# Firebase config

# Uncomment this if you'd like others to create their own Firebase project.
# For a team working on the same Firebase project(s), it is recommended to leave
# it commented so all members can deploy to the same project(s) in .firebaserc.
# .firebaserc

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
10 changes: 10 additions & 0 deletions Node/custom-url-shortener/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Custom shortlinks with Firestore and Firebase Hosting

1. Write a document to the `links` collection in Firestore to create a new shortLink:
```
{
longUrl: "https://firebase.google.com"
}
```
1. View the available shortlinks at the `/links` path on your Hosting site
1. Visit a shortlink's path on your hosting site `https://<your-site>/<shortlink>` to be redirected!
42 changes: 42 additions & 0 deletions Node/custom-url-shortener/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"hosting": {
"rewrites": [ {
"source": "/list",
"function": "listAllRedirects"
}, {
"source": "**",
"function": "redirectToFullURL"
}]
},
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
]
}
],
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"functions": {
"port": 5001
},
"firestore": {
"port": 8080
},
"hosting": {
"port": 5000
},
"ui": {
"enabled": true
},
"singleProjectMode": true
}
}
4 changes: 4 additions & 0 deletions Node/custom-url-shortener/firestore.indexes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"indexes": [],
"fieldOverrides": []
}
8 changes: 8 additions & 0 deletions Node/custom-url-shortener/firestore.rules
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /links/{linkId} {
allow write: if request.auth != null;
}
}
}
1 change: 1 addition & 0 deletions Node/custom-url-shortener/functions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
77 changes: 77 additions & 0 deletions Node/custom-url-shortener/functions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
const { onRequest } = require("firebase-functions/v2/https");
const logger = require("firebase-functions/logger");
const { onDocumentCreated } = require("firebase-functions/v2/firestore");

const { initializeApp } = require("firebase-admin/app");
const { getFirestore } = require("firebase-admin/firestore");

initializeApp();

exports.listAllRedirects = onRequest(async (request, response) => {
result = await getFirestore().collection("links").get();

response.type("json");
response.send(
JSON.stringify(
result.docs.map((docSnap) => docSnap.data()),
null,
2
)
);
});

exports.redirectToFullURL = onRequest(async (request, response) => {
const shortLink = request.path.split("/")[1];

if (!shortLink) {
response.status(404).send(`Invalid shortlink "${request.path}"`);
logger.info(`Invalid shortlink "${request.path}"`);
return;
}

const result = await getFirestore()
.collection("links")
.where("shortUrl", "==", request.path.split("/")[1])
.get();

if (result.docs.length === 0) {
response.status(404).send(`No entry found for shortlink "${shortLink}"`);
logger.info(`No entry found for shortlink "${shortLink}"`);
return;
} else if (result.docs.length > 1) {
response.status(500).send(
`Found too many URLs. Something is wrong`,
result.docs.map((docSnap) => docSnap.ref.id)
);
return;
}
const redirectUrl = result.docs[0].data().longUrl;

logger.info("redirect");
response.redirect(301, redirectUrl);
});

exports.shortenUrl = onDocumentCreated(
"links/{linkid}",
async (event, params) => {
const hash = (Math.random() + 1).toString(36).substring(7);

// check if the URL is valid
try {
new URL(event.data.data().longUrl);
} catch {
logger.error(
`invalid URL "${event.data.data().longUrl}"`,
event.data.data()
);
return;
}

await event.data.ref.update({ shortUrl: hash });
logger.info(`created shortlink`, {
documentId: params.linkid,
longUrl: event.data.data().longUrl,
shortLink: hash,
});
}
);
23 changes: 23 additions & 0 deletions Node/custom-url-shortener/functions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "18"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^11.8.0",
"firebase-functions": "^4.3.1"
},
"devDependencies": {
"firebase-functions-test": "^3.1.0"
},
"private": true
}
Loading
Loading