Files
angular.js/scripts/docs.angularjs.org-firebase/functions/index.js
T
Martin Staffa 8681fce27b chore(docs.angularjs.org): serve snapshots for googlebot
This commit restores serving the plain partials (content) when a docs
page is accessed with ?_escaped_fragment_=.
The Google Ajax Crawler accesses these urls when the page has
`<meta type="fragment" content="!">` is set.

During the migration to Firebase, this was lost, which resulted in Google
dropping the docs almost completely from the index.

We are using a Firebase cloud function to serve the partials. Since
we cannot access the static hosted files from the function, we have to
deploy them as part of the function directory instead, from which they
can be read.

Related to #16432
Related to #16417
2018-02-12 16:09:54 +01:00

50 lines
1.2 KiB
JavaScript

'use strict';
const functions = require('firebase-functions');
const fs = require('fs');
const BROWSER_CACHE_DURATION = 60 * 60;
const CDN_CACHE_DURATION = 60 * 60 * 12;
const headers = {
'Cache-Control': `public max-age=${BROWSER_CACHE_DURATION} s-maxage=${CDN_CACHE_DURATION}`
};
const buildSnapshot = data => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/">
</head>
<body>
${data}
</body>
</html>`;
function sendFile(request, response) {
const snapshotRequested = typeof request.query._escaped_fragment_ !== 'undefined';
const filePath = `content/${snapshotRequested ? `partials${request.path}` : 'index-production'}.html`;
if (snapshotRequested) {
fs.readFile(filePath, {encoding: 'utf8'}, (error, data) => {
if (error) {
response
.status(404)
.end();
} else {
response
.set(headers)
.send(buildSnapshot(data));
}
});
} else {
response
.set(headers)
.sendFile(filePath, {root: __dirname});
}
}
exports.sendFile = functions.https.onRequest(sendFile);