This repository has been archived by the owner on Aug 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
104 lines (93 loc) · 2.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import functions from "firebase-functions";
import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
import { routes, dirs } from "./routes.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const INDEX_TEMPLATE = fs
.readFileSync(path.resolve(__dirname, "index.html"))
.toString();
function metasForRoute(route) {
let metas = "";
for (const [key, value] of Object.entries(route)) {
metas += `<meta ${
key.startsWith("og:") ? "property" : "name"
}="${key}" content="${value}" />`;
}
return metas;
}
const BOT_AGENTS = [
"googlebot",
"yahoou",
"bingbot",
"baiduspider",
"yandex",
"yeti",
"yodaobot",
"gigabot",
"ia_archiver",
"facebookexternalhit",
"twitterbot",
"developers.google.com",
];
function isBot(userAgent) {
for (const bot of BOT_AGENTS) {
if (userAgent.toLowerCase().includes(bot)) {
return true;
}
}
return false;
}
const DEFAULT_METAS = {
fr: {
"og:title": "fullweb.dev",
"og:description": "Redécouvrir le développement Web",
"og:image": "https://fullweb.dev/images/social/social_fr.png",
},
en: {
"og:title": "fullweb.dev",
"og:description": "Relearn Web Development",
"og:image": "https://fullweb.dev/images/social/social_en.png",
},
};
export const httpRequestHandler = functions.https.onRequest(
(request, result) => {
let reqPath = request.path;
let lang = "fr";
const langPathMatch = /^\/(en|fr)(\/.*)/.exec(reqPath);
if (langPathMatch) {
[, lang, reqPath] = langPathMatch;
}
let route = routes[reqPath];
if (!route) {
const found = dirs.find(
([key, dirRoute]) => reqPath.startsWith(key) && dirRoute
) || ["", {}];
[, route] = found;
if (route[lang]) {
if (route.default) {
route = {
...route.default,
...route[lang],
};
} else {
route = route[lang];
}
}
route = {
...DEFAULT_METAS[lang],
...route,
};
}
let indexHTML = INDEX_TEMPLATE;
if (isBot(request.headers["user-agent"]) && route) {
indexHTML = indexHTML.replace(
/<!-- meta-tags:start -->[\s\S]*<!-- meta-tags:end -->/,
metasForRoute(route)
);
}
// caching
// res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
result.status(200).send(indexHTML);
}
);