-
-
Notifications
You must be signed in to change notification settings - Fork 933
/
plugin.ts
331 lines (316 loc) · 11 KB
/
plugin.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { Type } from '@vendure/common/lib/shared-types';
import {
AssetStorageStrategy,
createProxyHandler,
LocalAssetStorageStrategy,
OnVendureBootstrap,
OnVendureClose,
RuntimeVendureConfig,
VendurePlugin,
} from '@vendure/core';
import express, { NextFunction, Request, Response } from 'express';
import { Server } from 'http';
import path from 'path';
import { SharpAssetPreviewStrategy } from './sharp-asset-preview-strategy';
import { transformImage } from './transform-image';
/**
* @description
* Specifies the way in which an asset preview image will be resized to fit in the
* proscribed dimensions:
*
* * crop: crops the image to cover both provided dimensions
* * resize: Preserving aspect ratio, resizes the image to be as large as possible
* while ensuring its dimensions are less than or equal to both those specified.
*
* @docsCategory AssetServerPlugin
*/
export type ImageTransformMode = 'crop' | 'resize';
/**
* @description
* A configuration option for an image size preset for the AssetServerPlugin.
*
* Presets allow a shorthand way to generate a thumbnail preview of an asset. For example,
* the built-in "tiny" preset generates a 50px x 50px cropped preview, which can be accessed
* by appending the string `preset=tiny` to the asset url:
*
* `http://localhost:3000/assets/some-asset.jpg?preset=tiny`
*
* is equivalent to:
*
* `http://localhost:3000/assets/some-asset.jpg?w=50&h=50&mode=crop`
*
* @docsCategory AssetServerPlugin
*/
export interface ImageTransformPreset {
name: string;
width: number;
height: number;
mode: ImageTransformMode;
}
/**
* @description
* The configuration options for the AssetServerPlugin.
*
* @docsCategory AssetServerPlugin
*/
export interface AssetServerOptions {
hostname?: string;
/**
* @description
* The local port that the server will run on. Note that the AssetServerPlugin
* includes a proxy server which allows the asset server to be accessed on the same
* port as the main Vendure server.
*/
port: number;
/**
* @description
* The proxy route to the asset server.
*/
route: string;
/**
* @description
* The local directory to which assets will be uploaded.
*/
assetUploadDir: string;
/**
* @description
* The complete URL prefix of the asset files. For example, "https://demo.vendure.io/assets/"
*
* If not provided, the plugin will attempt to guess based off the incoming
* request and the configured route. However, in all but the simplest cases,
* this guess may not yield correct results.
*/
assetUrlPrefix?: string;
/**
* @description
* The max width in pixels of a generated preview image.
*
* @default 1600
*/
previewMaxWidth?: number;
/**
* @description
* The max height in pixels of a generated preview image.
*
* @default 1600
*/
previewMaxHeight?: number;
/**
* @description
* An array of additional {@link ImageTransformPreset} objects.
*/
presets?: ImageTransformPreset[];
}
/**
* @description
* The `AssetServerPlugin` serves assets (images and other files) from the local file system. It can also perform on-the-fly image transformations
* and caches the results for subsequent calls.
*
* ## Installation
*
* `yarn add \@vendure/asset-server-plugin`
*
* or
*
* `npm install \@vendure/asset-server-plugin`
*
* @example
* ```ts
* import { AssetServerPlugin } from '\@vendure/asset-server-plugin';
*
* const config: VendureConfig = {
* // Add an instance of the plugin to the plugins array
* plugins: [
* AssetServerPlugin.init({
* route: 'assets',
* assetUploadDir: path.join(__dirname, 'assets'),
* port: 4000,
* }),
* ],
* };
* ```
*
* The full configuration is documented at [AssetServerOptions]({{< relref "asset-server-options" >}})
*
* ## Image transformation
*
* Asset preview images can be transformed (resized & cropped) on the fly by appending query parameters to the url:
*
* `http://localhost:3000/assets/some-asset.jpg?w=500&h=300&mode=resize`
*
* The above URL will return `some-asset.jpg`, resized to fit in the bounds of a 500px x 300px rectangle.
*
* ### Preview mode
*
* The `mode` parameter can be either `crop` or `resize`. See the [ImageTransformMode]({{< relref "image-transform-mode" >}}) docs for details.
*
* ### Transform presets
*
* Presets can be defined which allow a single preset name to be used instead of specifying the width, height and mode. Presets are
* configured via the AssetServerOptions [presets property]({{< relref "asset-server-options" >}}#presets).
*
* For example, defining the following preset:
*
* ```ts
* new AssetServerPlugin({
* // ...
* presets: [
* { name: 'my-preset', width: 85, height: 85, mode: 'crop' },
* ],
* }),
* ```
*
* means that a request to:
*
* `http://localhost:3000/assets/some-asset.jpg?preset=my-preset`
*
* is equivalent to:
*
* `http://localhost:3000/assets/some-asset.jpg?w=85&h=85&mode=crop`
*
* The AssetServerPlugin comes pre-configured with the following presets:
*
* name | width | height | mode
* -----|-------|--------|-----
* tiny | 50px | 50px | crop
* thumb | 150px | 150px | crop
* small | 300px | 300px | resize
* medium | 500px | 500px | resize
* large | 800px | 800px | resize
*
* @docsCategory AssetServerPlugin
*/
@VendurePlugin({
configuration: config => AssetServerPlugin.configure(config),
})
export class AssetServerPlugin implements OnVendureBootstrap, OnVendureClose {
private server: Server;
private static assetStorage: AssetStorageStrategy;
private readonly cacheDir = 'cache';
private presets: ImageTransformPreset[] = [
{ name: 'tiny', width: 50, height: 50, mode: 'crop' },
{ name: 'thumb', width: 150, height: 150, mode: 'crop' },
{ name: 'small', width: 300, height: 300, mode: 'resize' },
{ name: 'medium', width: 500, height: 500, mode: 'resize' },
{ name: 'large', width: 800, height: 800, mode: 'resize' },
];
private static options: AssetServerOptions;
/**
* @description
* Set the plugin options.
*/
static init(options: AssetServerOptions): Type<AssetServerPlugin> {
AssetServerPlugin.options = options;
return this;
}
/** @internal */
static configure(config: RuntimeVendureConfig) {
this.assetStorage = this.createAssetStorageStrategy(this.options);
config.assetOptions.assetPreviewStrategy = new SharpAssetPreviewStrategy({
maxWidth: this.options.previewMaxWidth || 1600,
maxHeight: this.options.previewMaxHeight || 1600,
});
config.assetOptions.assetStorageStrategy = this.assetStorage;
config.middleware.push({
handler: createProxyHandler({ ...this.options, label: 'Asset Server' }),
route: this.options.route,
});
return config;
}
/** @internal */
onVendureBootstrap(): void | Promise<void> {
if (AssetServerPlugin.options.presets) {
for (const preset of AssetServerPlugin.options.presets) {
const existingIndex = this.presets.findIndex(p => p.name === preset.name);
if (-1 < existingIndex) {
this.presets.splice(existingIndex, 1, preset);
} else {
this.presets.push(preset);
}
}
}
this.createAssetServer();
}
/** @internal */
onVendureClose(): Promise<void> {
return new Promise(resolve => {
this.server.close(() => resolve());
});
}
private static createAssetStorageStrategy(options: AssetServerOptions) {
const { assetUrlPrefix, assetUploadDir, route } = options;
const toAbsoluteUrlFn = (request: Request, identifier: string): string => {
if (!identifier) {
return '';
}
const prefix = assetUrlPrefix || `${request.protocol}://${request.get('host')}/${route}/`;
return identifier.startsWith(prefix) ? identifier : `${prefix}${identifier}`;
};
return new LocalAssetStorageStrategy(assetUploadDir, toAbsoluteUrlFn);
}
/**
* Creates the image server instance
*/
private createAssetServer() {
const assetServer = express();
assetServer.use(this.serveStaticFile(), this.generateTransformedImage());
this.server = assetServer.listen(AssetServerPlugin.options.port);
}
/**
* Sends the file requested to the broswer.
*/
private serveStaticFile() {
return (req: Request, res: Response) => {
const filePath = path.join(
AssetServerPlugin.options.assetUploadDir,
this.getFileNameFromRequest(req),
);
res.sendFile(filePath);
};
}
/**
* If an exception was thrown by the first handler, then it may be because a transformed image
* is being requested which does not yet exist. In this case, this handler will generate the
* transformed image, save it to cache, and serve the result as a response.
*/
private generateTransformedImage() {
return async (err: any, req: Request, res: Response, next: NextFunction) => {
if (err && err.status === 404) {
if (req.query) {
let file: Buffer;
try {
file = await AssetServerPlugin.assetStorage.readFileToBuffer(req.path);
} catch (err) {
res.status(404).send('Resource not found');
return;
}
const image = await transformImage(file, req.query, this.presets || []);
const imageBuffer = await image.toBuffer();
const cachedFileName = this.getFileNameFromRequest(req);
await AssetServerPlugin.assetStorage.writeFileFromBuffer(cachedFileName, imageBuffer);
res.set('Content-Type', `image/${(await image.metadata()).format}`);
res.send(imageBuffer);
}
}
next();
};
}
private getFileNameFromRequest(req: Request): string {
if (req.query.w || req.query.h) {
const width = req.query.w || '';
const height = req.query.h || '';
const mode = req.query.mode || '';
return this.cacheDir + '/' + this.addSuffix(req.path, `_transform_w${width}_h${height}_m${mode}`);
} else if (req.query.preset) {
if (this.presets && !!this.presets.find(p => p.name === req.query.preset)) {
return this.cacheDir + '/' + this.addSuffix(req.path, `_transform_pre_${req.query.preset}`);
}
}
return req.path;
}
private addSuffix(fileName: string, suffix: string): string {
const ext = path.extname(fileName);
const baseName = path.basename(fileName, ext);
return `${baseName}${suffix}${ext}`;
}
}