plugin.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import { MiddlewareConsumer, NestModule, OnApplicationBootstrap } from '@nestjs/common';
  2. import { Type } from '@vendure/common/lib/shared-types';
  3. import {
  4. AssetStorageStrategy,
  5. Logger,
  6. PluginCommonModule,
  7. RuntimeVendureConfig,
  8. VendurePlugin,
  9. } from '@vendure/core';
  10. import { createHash } from 'crypto';
  11. import express, { NextFunction, Request, Response } from 'express';
  12. import { fromBuffer } from 'file-type';
  13. import fs from 'fs-extra';
  14. import path from 'path';
  15. import { loggerCtx } from './constants';
  16. import { defaultAssetStorageStrategyFactory } from './default-asset-storage-strategy-factory';
  17. import { HashedAssetNamingStrategy } from './hashed-asset-naming-strategy';
  18. import { SharpAssetPreviewStrategy } from './sharp-asset-preview-strategy';
  19. import { transformImage } from './transform-image';
  20. import { AssetServerOptions, ImageTransformPreset } from './types';
  21. /**
  22. * @description
  23. * The `AssetServerPlugin` serves assets (images and other files) from the local file system, and can also be configured to use
  24. * other storage strategies (e.g. {@link S3AssetStorageStrategy}. It can also perform on-the-fly image transformations
  25. * and caches the results for subsequent calls.
  26. *
  27. * ## Installation
  28. *
  29. * `yarn add \@vendure/asset-server-plugin`
  30. *
  31. * or
  32. *
  33. * `npm install \@vendure/asset-server-plugin`
  34. *
  35. * @example
  36. * ```ts
  37. * import { AssetServerPlugin } from '\@vendure/asset-server-plugin';
  38. *
  39. * const config: VendureConfig = {
  40. * // Add an instance of the plugin to the plugins array
  41. * plugins: [
  42. * AssetServerPlugin.init({
  43. * route: 'assets',
  44. * assetUploadDir: path.join(__dirname, 'assets'),
  45. * port: 4000,
  46. * }),
  47. * ],
  48. * };
  49. * ```
  50. *
  51. * The full configuration is documented at [AssetServerOptions]({{< relref "asset-server-options" >}})
  52. *
  53. * ## Image transformation
  54. *
  55. * Asset preview images can be transformed (resized & cropped) on the fly by appending query parameters to the url:
  56. *
  57. * `http://localhost:3000/assets/some-asset.jpg?w=500&h=300&mode=resize`
  58. *
  59. * The above URL will return `some-asset.jpg`, resized to fit in the bounds of a 500px x 300px rectangle.
  60. *
  61. * ### Preview mode
  62. *
  63. * The `mode` parameter can be either `crop` or `resize`. See the [ImageTransformMode]({{< relref "image-transform-mode" >}}) docs for details.
  64. *
  65. * ### Focal point
  66. *
  67. * When cropping an image (`mode=crop`), Vendure will attempt to keep the most "interesting" area of the image in the cropped frame. It does this
  68. * by finding the area of the image with highest entropy (the busiest area of the image). However, sometimes this does not yield a satisfactory
  69. * result - part or all of the main subject may still be cropped out.
  70. *
  71. * This is where specifying the focal point can help. The focal point of the image may be specified by passing the `fpx` and `fpy` query parameters.
  72. * These are normalized coordinates (i.e. a number between 0 and 1), so the `fpx=0&fpy=0` corresponds to the top left of the image.
  73. *
  74. * For example, let's say there is a very wide landscape image which we want to crop to be square. The main subject is a house to the far left of the
  75. * image. The following query would crop it to a square with the house centered:
  76. *
  77. * `http://localhost:3000/assets/landscape.jpg?w=150&h=150&mode=crop&fpx=0.2&fpy=0.7`
  78. *
  79. * ### Transform presets
  80. *
  81. * Presets can be defined which allow a single preset name to be used instead of specifying the width, height and mode. Presets are
  82. * configured via the AssetServerOptions [presets property]({{< relref "asset-server-options" >}}#presets).
  83. *
  84. * For example, defining the following preset:
  85. *
  86. * ```ts
  87. * new AssetServerPlugin({
  88. * // ...
  89. * presets: [
  90. * { name: 'my-preset', width: 85, height: 85, mode: 'crop' },
  91. * ],
  92. * }),
  93. * ```
  94. *
  95. * means that a request to:
  96. *
  97. * `http://localhost:3000/assets/some-asset.jpg?preset=my-preset`
  98. *
  99. * is equivalent to:
  100. *
  101. * `http://localhost:3000/assets/some-asset.jpg?w=85&h=85&mode=crop`
  102. *
  103. * The AssetServerPlugin comes pre-configured with the following presets:
  104. *
  105. * name | width | height | mode
  106. * -----|-------|--------|-----
  107. * tiny | 50px | 50px | crop
  108. * thumb | 150px | 150px | crop
  109. * small | 300px | 300px | resize
  110. * medium | 500px | 500px | resize
  111. * large | 800px | 800px | resize
  112. *
  113. * ### Caching
  114. * By default, the AssetServerPlugin will cache every transformed image, so that the transformation only needs to be performed a single time for
  115. * a given configuration. Caching can be disabled per-request by setting the `?cache=false` query parameter.
  116. *
  117. * @docsCategory AssetServerPlugin
  118. */
  119. @VendurePlugin({
  120. imports: [PluginCommonModule],
  121. configuration: config => AssetServerPlugin.configure(config),
  122. })
  123. export class AssetServerPlugin implements NestModule, OnApplicationBootstrap {
  124. private static assetStorage: AssetStorageStrategy;
  125. private readonly cacheDir = 'cache';
  126. private presets: ImageTransformPreset[] = [
  127. { name: 'tiny', width: 50, height: 50, mode: 'crop' },
  128. { name: 'thumb', width: 150, height: 150, mode: 'crop' },
  129. { name: 'small', width: 300, height: 300, mode: 'resize' },
  130. { name: 'medium', width: 500, height: 500, mode: 'resize' },
  131. { name: 'large', width: 800, height: 800, mode: 'resize' },
  132. ];
  133. private static options: AssetServerOptions;
  134. /**
  135. * @description
  136. * Set the plugin options.
  137. */
  138. static init(options: AssetServerOptions): Type<AssetServerPlugin> {
  139. AssetServerPlugin.options = options;
  140. return this;
  141. }
  142. /** @internal */
  143. static async configure(config: RuntimeVendureConfig) {
  144. const storageStrategyFactory =
  145. this.options.storageStrategyFactory || defaultAssetStorageStrategyFactory;
  146. this.assetStorage = await storageStrategyFactory(this.options);
  147. config.assetOptions.assetPreviewStrategy = new SharpAssetPreviewStrategy({
  148. maxWidth: this.options.previewMaxWidth || 1600,
  149. maxHeight: this.options.previewMaxHeight || 1600,
  150. });
  151. config.assetOptions.assetStorageStrategy = this.assetStorage;
  152. config.assetOptions.assetNamingStrategy =
  153. this.options.namingStrategy || new HashedAssetNamingStrategy();
  154. return config;
  155. }
  156. /** @internal */
  157. onApplicationBootstrap(): void | Promise<void> {
  158. if (AssetServerPlugin.options.presets) {
  159. for (const preset of AssetServerPlugin.options.presets) {
  160. const existingIndex = this.presets.findIndex(p => p.name === preset.name);
  161. if (-1 < existingIndex) {
  162. this.presets.splice(existingIndex, 1, preset);
  163. } else {
  164. this.presets.push(preset);
  165. }
  166. }
  167. }
  168. const cachePath = path.join(AssetServerPlugin.options.assetUploadDir, this.cacheDir);
  169. fs.ensureDirSync(cachePath);
  170. }
  171. configure(consumer: MiddlewareConsumer) {
  172. Logger.info('Creating asset server middleware', loggerCtx);
  173. consumer.apply(this.createAssetServer()).forRoutes(AssetServerPlugin.options.route);
  174. }
  175. /**
  176. * Creates the image server instance
  177. */
  178. private createAssetServer() {
  179. const assetServer = express.Router();
  180. assetServer.use(this.sendAsset(), this.generateTransformedImage());
  181. return assetServer;
  182. }
  183. /**
  184. * Reads the file requested and send the response to the browser.
  185. */
  186. private sendAsset() {
  187. return async (req: Request, res: Response, next: NextFunction) => {
  188. const key = this.getFileNameFromRequest(req);
  189. try {
  190. const file = await AssetServerPlugin.assetStorage.readFileToBuffer(key);
  191. let mimeType = this.getMimeType(key);
  192. if (!mimeType) {
  193. mimeType = (await fromBuffer(file))?.mime || 'application/octet-stream';
  194. }
  195. res.contentType(mimeType);
  196. res.send(file);
  197. } catch (e) {
  198. const err = new Error('File not found');
  199. (err as any).status = 404;
  200. return next(err);
  201. }
  202. };
  203. }
  204. /**
  205. * If an exception was thrown by the first handler, then it may be because a transformed image
  206. * is being requested which does not yet exist. In this case, this handler will generate the
  207. * transformed image, save it to cache, and serve the result as a response.
  208. */
  209. private generateTransformedImage() {
  210. return async (err: any, req: Request, res: Response, next: NextFunction) => {
  211. if (err && (err.status === 404 || err.statusCode === 404)) {
  212. if (req.query) {
  213. Logger.debug(`Pre-cached Asset not found: ${req.path}`, loggerCtx);
  214. let file: Buffer;
  215. try {
  216. file = await AssetServerPlugin.assetStorage.readFileToBuffer(req.path);
  217. } catch (err) {
  218. res.status(404).send('Resource not found');
  219. return;
  220. }
  221. const image = await transformImage(file, req.query as any, this.presets || []);
  222. try {
  223. const imageBuffer = await image.toBuffer();
  224. if (!req.query.cache || req.query.cache === 'true') {
  225. const cachedFileName = this.getFileNameFromRequest(req);
  226. await AssetServerPlugin.assetStorage.writeFileFromBuffer(
  227. cachedFileName,
  228. imageBuffer,
  229. );
  230. Logger.debug(`Saved cached asset: ${cachedFileName}`, loggerCtx);
  231. }
  232. res.set('Content-Type', `image/${(await image.metadata()).format}`);
  233. res.send(imageBuffer);
  234. return;
  235. } catch (e) {
  236. Logger.error(e, 'AssetServerPlugin', e.stack);
  237. res.status(500).send(e.message);
  238. return;
  239. }
  240. }
  241. }
  242. next();
  243. };
  244. }
  245. private getFileNameFromRequest(req: Request): string {
  246. const { w, h, mode, preset, fpx, fpy } = req.query;
  247. const focalPoint = fpx && fpy ? `_fpx${fpx}_fpy${fpy}` : '';
  248. let imageParamHash: string | null = null;
  249. if (w || h) {
  250. const width = w || '';
  251. const height = h || '';
  252. imageParamHash = this.md5(`_transform_w${width}_h${height}_m${mode}${focalPoint}`);
  253. } else if (preset) {
  254. if (this.presets && !!this.presets.find(p => p.name === preset)) {
  255. imageParamHash = this.md5(`_transform_pre_${preset}${focalPoint}`);
  256. }
  257. }
  258. if (imageParamHash) {
  259. return path.join(this.cacheDir, this.addSuffix(req.path, imageParamHash));
  260. } else {
  261. return req.path;
  262. }
  263. }
  264. private md5(input: string): string {
  265. return createHash('md5').update(input).digest('hex');
  266. }
  267. private addSuffix(fileName: string, suffix: string): string {
  268. const ext = path.extname(fileName);
  269. const baseName = path.basename(fileName, ext);
  270. const dirName = path.dirname(fileName);
  271. return path.join(dirName, `${baseName}${suffix}${ext}`);
  272. }
  273. /**
  274. * Attempt to get the mime type from the file name.
  275. */
  276. private getMimeType(fileName: string): string | undefined {
  277. const ext = path.extname(fileName);
  278. switch (ext) {
  279. case '.jpg':
  280. case '.jpeg':
  281. return 'image/jpeg';
  282. case '.png':
  283. return 'image/png';
  284. case '.gif':
  285. return 'image/gif';
  286. case '.svg':
  287. return 'image/svg+xml';
  288. case '.tiff':
  289. return 'image/tiff';
  290. case '.webp':
  291. return 'image/webp';
  292. }
  293. }
  294. }