forked from cyrilwanner/optimized-images-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseQuery.ts
86 lines (73 loc) · 2.11 KB
/
parseQuery.ts
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
import querystring from 'querystring';
import { LoaderOptions } from './options';
export interface ImageOptions {
optimize: boolean;
resize: boolean;
width?: number;
height?: number;
convert?: 'webp';
forceInline?: boolean;
forceUrl?: boolean;
processLoaders?: boolean;
component?: 'react';
lqip?: 'blur' | 'colors';
}
/**
* Parses a query string into image options
*
* @param {string} rawQuery Resource query
* @param {LoaderOptions} loaderOptions Optimized images loader options
* @returns {ImageOptions} Image options
*/
const parseQuery = (rawQuery: string, loaderOptions: LoaderOptions): ImageOptions => {
const query = querystring.parse(rawQuery.substr(0, 1) === '?' ? rawQuery.substr(1) : rawQuery);
const options: ImageOptions = {
optimize: loaderOptions.optimize !== false,
resize: false,
};
// disable optimization
if (typeof query.original !== 'undefined') {
options.optimize = false;
}
// force inline
if (typeof query.inline !== 'undefined') {
options.forceInline = true;
}
// force url
if (typeof query.url !== 'undefined') {
options.forceUrl = true;
}
// include raw image (used for svg)
if (typeof query.include !== 'undefined') {
options.processLoaders = false;
if (loaderOptions.includeStrategy === 'react') {
options.component = 'react';
}
}
// resize image
if (typeof query.width === 'string') {
options.width = parseInt(query.width, 10);
options.resize = true;
}
if (typeof query.height === 'string') {
options.height = parseInt(query.height, 10);
options.resize = true;
}
// convert image to webp
if (typeof query.webp !== 'undefined') {
options.convert = 'webp';
}
// return low quality image placeholder
if (typeof query.lqip !== 'undefined') {
options.resize = true;
options.optimize = false;
options.lqip = 'blur';
}
// return dominant colors instead of image
if (typeof query.colors !== 'undefined' || typeof query['lqip-colors'] !== 'undefined') {
options.processLoaders = false;
options.lqip = 'colors';
}
return options;
};
export default parseQuery;