forked from angular/angular.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
75 lines (61 loc) · 2.24 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
'use strict';
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const path = require('path');
const gcsBucketId = `${process.env.GCLOUD_PROJECT}.appspot.com`;
const LOCAL_TMP_FOLDER = '/tmp/';
const BROWSER_CACHE_DURATION = 300;
const CDN_CACHE_DURATION = 600;
function sendStoredFile(request, response) {
let filePathSegments = request.path.split('/').filter((segment) => {
// Remove empty leading or trailing path parts
return segment !== '';
});
const version = filePathSegments[0];
const isDocsPath = filePathSegments[1] === 'docs';
const lastSegment = filePathSegments[filePathSegments.length - 1];
const bucket = gcs.bucket(gcsBucketId);
let downloadSource;
let downloadDestination;
let fileName;
if (isDocsPath && filePathSegments.length === 2) {
fileName = 'index.html';
filePathSegments = [version, 'docs', fileName];
} else {
fileName = lastSegment;
}
downloadSource = path.join.apply(null, filePathSegments);
downloadDestination = `${LOCAL_TMP_FOLDER}${fileName}`;
downloadAndSend(downloadSource, downloadDestination).catch(error => {
if (isDocsPath && error.code === 404) {
fileName = 'index.html';
filePathSegments = [version, 'docs', fileName];
downloadSource = path.join.apply(null, filePathSegments);
downloadDestination = `${LOCAL_TMP_FOLDER}${fileName}`;
return downloadAndSend(downloadSource, downloadDestination);
}
return Promise.reject(error);
}).catch(error => {
let message = 'General error';
if (error.code === 404) {
if (fileName.split('.').length === 1) {
message = 'Directory listing is not supported';
} else {
message = 'File not found';
}
}
return response.status(error.code).send(message);
});
function downloadAndSend(downloadSource, downloadDestination) {
return bucket.file(downloadSource).download({
destination: downloadDestination
}).then(() => {
return response.status(200)
.set({
'Cache-Control': `public, max-age=${BROWSER_CACHE_DURATION}, s-maxage=${CDN_CACHE_DURATION}`
})
.sendFile(downloadDestination);
});
}
}
exports.sendStoredFile = functions.https.onRequest(sendStoredFile);