Demo: https://s.duyet.net
Mã nguồn: https://github.com/duyetdev/firebase-shorten-url
Service sử dụng:
- Firebase Functions
- Firebase Hosting
- Dynamic Link
Bước 1: Cài đặt Firebase Functions
theo các bước ở đây: https://firebase.google.com/docs/functions/get-started bao gồm
- Initialize Firebase SDK for Cloud Functions
- Kích hoạt Dynamic Link
- Mã nguồn cho API
- Deploy Firebase Functions:
API và Redirect link, cấu hình trong
Để test local, mở 2 terminal để chạy firebase functions và Gatsby hosting:
Để build và deploy hosting:
Kết quả: https://s.duyet.net
Hiện tại link được tạo bởi Dynamic Link không hiện trên Firebase Dashboard, và chưa thể custom được keyword như trên Firebase Dashboard.
- Mã nguồn cho API
addUrlconst axios = require('axios');
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
const app = admin.initializeApp();
const config = functions.config().config
const apiKey = process.env.API_KEY || config.api_key || app.options_.apiKey
const firebaseDynamicLinkApi = `https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${apiKey}`;
const domainUriPrefix = config.domain_uri_prefix || 'https://duyeturl.page.link';
exports.addUrl = functions.https.onRequest(async (req, res) => {
const link = req.query.url || req.body.url || null;
try {
let result = await axios.post(firebaseDynamicLinkApi, {
dynamicLinkInfo: {
domainUriPrefix,
link,
},
suffix: {
option: 'SHORT'
}
})
res.json(result.data)
} catch (e) {
console.error(e.message)
res.status(500).json('error')
}
});
- Deploy Firebase Functions:
firebase deploy --only functions
Bước 2: Firebase Hosting, Web UI
Website mình sử dụng Gatsby React, mã nguồn tại thư mục hosting: https://github.com/duyetdev/firebase-shorten-url/tree/master/hostingAPI và Redirect link, cấu hình trong
firebase.json, chú ý dòng rewrites /api/add và /r/**{
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint"
],
"source": "functions"
},
"hosting": {
"cleanUrls": true,
"trailingSlash": false,
"public": "hosting/public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{ "source": "/api/add", "function": "addUrl" },
{ "source": "/r/**", "dynamicLinks": true },
{
"source": "**",
"destination": "/index.html"
}
]
}
}
Để test local, mở 2 terminal để chạy firebase functions và Gatsby hosting:
firebase serve
cd hosting && npm run develop
Để build và deploy hosting:
cd hosting && npm run build && firebase deploy
Kết quả: https://s.duyet.net
Hiện tại link được tạo bởi Dynamic Link không hiện trên Firebase Dashboard, và chưa thể custom được keyword như trên Firebase Dashboard.



Tôi là Duyệt