-
Notifications
You must be signed in to change notification settings - Fork 466
/
Copy pathpathUtils.js
102 lines (82 loc) · 2.82 KB
/
pathUtils.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
'use strict';
const _ = require('lodash');
const URL = require('url-parse');
const SHA1 = require("crypto-js/sha1");
const defaultImageTypes = ['png', 'jpeg', 'jpg', 'gif', 'bmp', 'tiff', 'tif'];
function serializeObjectKeys(obj) {
return _(obj)
.toPairs()
.sortBy(a => a[0])
.map(a => a[1])
.value();
}
function getQueryForCacheKey(url, useQueryParamsInCacheKey) {
if (_.isArray(useQueryParamsInCacheKey)) {
return serializeObjectKeys(_.pick(url.query, useQueryParamsInCacheKey));
}
if (useQueryParamsInCacheKey) {
return serializeObjectKeys(url.query);
}
return '';
}
function generateCacheKey(url, useQueryParamsInCacheKey = true) {
const parsedUrl = new URL(url, null, true);
const pathParts = parsedUrl.pathname.split('/');
// last path part is the file name
const fileName = pathParts.pop();
const filePath = pathParts.join('/');
const parts = fileName.split('.');
const fileType = parts.length > 1 ? _.toLower(parts.pop()) : '';
const type = defaultImageTypes.includes(fileType) ? fileType : 'jpg';
const cacheable = filePath + fileName + type + getQueryForCacheKey(parsedUrl, useQueryParamsInCacheKey);
return SHA1(cacheable) + '.' + type;
}
function getHostCachePathComponent(url) {
const {
host
} = new URL(url);
return host.replace(/\.:/gi, '_').replace(/[^a-z0-9_]/gi, '_').toLowerCase()
+ '_' + SHA1(host);
}
/**
* handle the resolution of URLs to local file paths
*/
module.exports = {
/**
* Given a URL and some options returns the file path in the file system corresponding to it's cached image location
* @param url
* @param cacheLocation
* @returns {string}
*/
getImageFilePath(url, cacheLocation) {
const hostCachePath = getHostCachePathComponent(url);
const cacheKey = generateCacheKey(url);
return `${cacheLocation}/${hostCachePath}/${cacheKey}`;
},
/**
* Given a URL returns the relative file path combined from host and url hash
* @param url
* @returns {string}
*/
getImageRelativeFilePath(url) {
const hostCachePath = getHostCachePathComponent(url);
const cacheKey = generateCacheKey(url);
return `${hostCachePath}/${cacheKey}`;
},
/**
* returns the url after removing all unused query params
* @param url
* @param useQueryParamsInCacheKey
* @returns {string}
*/
getCacheableUrl(url, useQueryParamsInCacheKey) {
const parsedUrl = new URL(url, null, true);
if (_.isArray(useQueryParamsInCacheKey)) {
parsedUrl.set('query', _.pick(parsedUrl.query, useQueryParamsInCacheKey));
}
if (!useQueryParamsInCacheKey) {
parsedUrl.set('query', {});
}
return parsedUrl.toString();
}
};