plugin.ts 11 KB

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