plugin.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import { AssetStorageStrategy, createProxyHandler, InjectorFn, LocalAssetStorageStrategy, VendureConfig, VendurePlugin } from '@vendure/core';
  2. import express, { NextFunction, Request, Response } from 'express';
  3. import { Server } from 'http';
  4. import path from 'path';
  5. import { SharpAssetPreviewStrategy } from './sharp-asset-preview-strategy';
  6. import { transformImage } from './transform-image';
  7. /**
  8. * @description
  9. * Specifies the way in which an asset preview image will be resized to fit in the
  10. * proscribed dimensions:
  11. *
  12. * * crop: crops the image to cover both provided dimensions
  13. * * resize: Preserving aspect ratio, resizes the image to be as large as possible
  14. * while ensuring its dimensions are less than or equal to both those specified.
  15. *
  16. * @docsCategory AssetServerPlugin
  17. */
  18. export type ImageTransformMode = 'crop' | 'resize';
  19. /**
  20. * @description
  21. * A configuration option for an image size preset for the AssetServerPlugin.
  22. *
  23. * Presets allow a shorthand way to generate a thumbnail preview of an asset. For example,
  24. * the built-in "tiny" preset generates a 50px x 50px cropped preview, which can be accessed
  25. * by appending the string `preset=tiny` to the asset url:
  26. *
  27. * `http://localhost:3000/assets/some-asset.jpg?preset=tiny`
  28. *
  29. * is equivalent to:
  30. *
  31. * `http://localhost:3000/assets/some-asset.jpg?w=50&h=50&mode=crop`
  32. *
  33. * @docsCategory AssetServerPlugin
  34. */
  35. export interface ImageTransformPreset {
  36. name: string;
  37. width: number;
  38. height: number;
  39. mode: ImageTransformMode;
  40. }
  41. /**
  42. * @description
  43. * The configuration options for the AssetServerPlugin.
  44. *
  45. * @docsCategory AssetServerPlugin
  46. */
  47. export interface AssetServerOptions {
  48. hostname?: string;
  49. /**
  50. * @description
  51. * The local port that the server will run on. Note that the AssetServerPlugin
  52. * includes a proxy server which allows the asset server to be accessed on the same
  53. * port as the main Vendure server.
  54. */
  55. port: number;
  56. /**
  57. * @description
  58. * The proxy route to the asset server.
  59. */
  60. route: string;
  61. /**
  62. * @description
  63. * The local directory to which assets will be uploaded.
  64. */
  65. assetUploadDir: string;
  66. /**
  67. * @description
  68. * The max width in pixels of a generated preview image.
  69. *
  70. * @default 1600
  71. */
  72. previewMaxWidth?: number;
  73. /**
  74. * @description
  75. * The max height in pixels of a generated preview image.
  76. *
  77. * @default 1600
  78. */
  79. previewMaxHeight?: number;
  80. /**
  81. * @description
  82. * An array of additional {@link ImageTransformPreset} objects.
  83. */
  84. presets?: ImageTransformPreset[];
  85. }
  86. /**
  87. * @description
  88. * The `AssetServerPlugin` serves assets (images and other files) from the local file system. It can also perform on-the-fly image transformations
  89. * and caches the results for subsequent calls.
  90. *
  91. * ## Installation
  92. *
  93. * `yarn add @vendure/asset-server-plugin`
  94. *
  95. * or
  96. *
  97. * `npm install @vendure/asset-server-plugin`
  98. *
  99. * @example
  100. * ```ts
  101. * import { AssetServerPlugin } from '@vendure/asset-server-plugin';
  102. *
  103. * const config: VendureConfig = {
  104. * // Add an instance of the plugin to the plugins array
  105. * plugins: [
  106. * new AssetServerPlugin({
  107. * route: 'assets',
  108. * assetUploadDir: path.join(__dirname, 'assets'),
  109. * port: 4000,
  110. * }),
  111. * ],
  112. * };
  113. * ```
  114. *
  115. * The full configuration is documented at [AssetServerOptions]({{< relref "asset-server-options" >}})
  116. *
  117. * ## Image transformation
  118. *
  119. * Asset preview images can be transformed (resized & cropped) on the fly by appending query parameters to the url:
  120. *
  121. * `http://localhost:3000/assets/some-asset.jpg?w=500&h=300&mode=resize`
  122. *
  123. * The above URL will return `some-asset.jpg`, resized to fit in the bounds of a 500px x 300px rectangle.
  124. *
  125. * ### Preview mode
  126. *
  127. * The `mode` parameter can be either `crop` or `resize`. See the [ImageTransformMode]({{< relref "image-transform-mode" >}}) docs for details.
  128. *
  129. * ### Transform presets
  130. *
  131. * Presets can be defined which allow a single preset name to be used instead of specifying the width, height and mode. Presets are
  132. * configured via the AssetServerOptions [presets property]({{< relref "asset-server-options" >}}#presets).
  133. *
  134. * For example, defining the following preset:
  135. *
  136. * ```ts
  137. * new AssetServerPlugin({
  138. * // ...
  139. * presets: [
  140. * { name: 'my-preset', width: 85, height: 85, mode: 'crop' },
  141. * ],
  142. * }),
  143. * ```
  144. *
  145. * means that a request to:
  146. *
  147. * `http://localhost:3000/assets/some-asset.jpg?preset=my-preset`
  148. *
  149. * is equivalent to:
  150. *
  151. * `http://localhost:3000/assets/some-asset.jpg?w=85&h=85&mode=crop`
  152. *
  153. * The AssetServerPlugin comes pre-configured with the following presets:
  154. *
  155. * name | width | height | mode
  156. * -----|-------|--------|-----
  157. * tiny | 50px | 50px | crop
  158. * thumb | 150px | 150px | crop
  159. * small | 300px | 300px | resize
  160. * medium | 500px | 500px | resize
  161. * large | 800px | 800px | resize
  162. *
  163. * @docsCategory AssetServerPlugin
  164. */
  165. export class AssetServerPlugin implements VendurePlugin {
  166. private server: Server;
  167. private assetStorage: AssetStorageStrategy;
  168. private readonly cacheDir = 'cache';
  169. private readonly presets: ImageTransformPreset[] = [
  170. { name: 'tiny', width: 50, height: 50, mode: 'crop' },
  171. { name: 'thumb', width: 150, height: 150, mode: 'crop' },
  172. { name: 'small', width: 300, height: 300, mode: 'resize' },
  173. { name: 'medium', width: 500, height: 500, mode: 'resize' },
  174. { name: 'large', width: 800, height: 800, mode: 'resize' },
  175. ];
  176. constructor(private options: AssetServerOptions) {
  177. if (options.presets) {
  178. for (const preset of options.presets) {
  179. const existingIndex = this.presets.findIndex(p => p.name === preset.name);
  180. if (-1 < existingIndex) {
  181. this.presets.splice(existingIndex, 1, preset);
  182. } else {
  183. this.presets.push(preset);
  184. }
  185. }
  186. }
  187. }
  188. configure(config: Required<VendureConfig>) {
  189. this.assetStorage = this.createAssetStorageStrategy();
  190. config.assetOptions.assetPreviewStrategy = new SharpAssetPreviewStrategy({
  191. maxWidth: this.options.previewMaxWidth || 1600,
  192. maxHeight: this.options.previewMaxHeight || 1600,
  193. });
  194. config.assetOptions.assetStorageStrategy = this.assetStorage;
  195. config.middleware.push({
  196. handler: createProxyHandler({ ...this.options, label: 'Asset Server' }),
  197. route: this.options.route,
  198. });
  199. return config;
  200. }
  201. onBootstrap(inject: InjectorFn): void | Promise<void> {
  202. this.createAssetServer();
  203. }
  204. onClose(): Promise<void> {
  205. return new Promise(resolve => {
  206. this.server.close(() => resolve());
  207. });
  208. }
  209. private createAssetStorageStrategy() {
  210. const toAbsoluteUrlFn = (request: Request, identifier: string): string => {
  211. if (!identifier) {
  212. return '';
  213. }
  214. return `${request.protocol}://${request.get('host')}/${this.options.route}/${identifier}`;
  215. };
  216. return new LocalAssetStorageStrategy(this.options.assetUploadDir, toAbsoluteUrlFn);
  217. }
  218. /**
  219. * Creates the image server instance
  220. */
  221. private createAssetServer() {
  222. const assetServer = express();
  223. assetServer.use(this.serveStaticFile(), this.generateTransformedImage());
  224. this.server = assetServer.listen(this.options.port);
  225. }
  226. /**
  227. * Sends the file requested to the broswer.
  228. */
  229. private serveStaticFile() {
  230. return (req: Request, res: Response) => {
  231. const filePath = path.join(this.options.assetUploadDir, this.getFileNameFromRequest(req));
  232. res.sendFile(filePath);
  233. };
  234. }
  235. /**
  236. * If an exception was thrown by the first handler, then it may be because a transformed image
  237. * is being requested which does not yet exist. In this case, this handler will generate the
  238. * transformed image, save it to cache, and serve the result as a response.
  239. */
  240. private generateTransformedImage() {
  241. return async (err: any, req: Request, res: Response, next: NextFunction) => {
  242. if (err && err.status === 404) {
  243. if (req.query) {
  244. let file: Buffer;
  245. try {
  246. file = await this.assetStorage.readFileToBuffer(req.path);
  247. } catch (err) {
  248. res.status(404).send('Resource not found');
  249. return;
  250. }
  251. const image = await transformImage(file, req.query, this.presets || []);
  252. const imageBuffer = await image.toBuffer();
  253. const cachedFileName = this.getFileNameFromRequest(req);
  254. await this.assetStorage.writeFileFromBuffer(cachedFileName, imageBuffer);
  255. res.set('Content-Type', `image/${(await image.metadata()).format}`);
  256. res.send(imageBuffer);
  257. }
  258. }
  259. next();
  260. };
  261. }
  262. private getFileNameFromRequest(req: Request): string {
  263. if (req.query.w || req.query.h) {
  264. const width = req.query.w || '';
  265. const height = req.query.h || '';
  266. const mode = req.query.mode || '';
  267. return this.cacheDir + '/' + this.addSuffix(req.path, `_transform_w${width}_h${height}_m${mode}`);
  268. } else if (req.query.preset) {
  269. if (this.presets && !!this.presets.find(p => p.name === req.query.preset)) {
  270. return this.cacheDir + '/' + this.addSuffix(req.path, `_transform_pre_${req.query.preset}`);
  271. }
  272. }
  273. return req.path;
  274. }
  275. private addSuffix(fileName: string, suffix: string): string {
  276. const ext = path.extname(fileName);
  277. const baseName = path.basename(fileName, ext);
  278. return `${baseName}${suffix}${ext}`;
  279. }
  280. }