asset-server-plugin.e2e-spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /* tslint:disable:no-non-null-assertion */
  2. import { DefaultLogger, LogLevel, mergeConfig } from '@vendure/core';
  3. import { AssetFragment } from '@vendure/core/e2e/graphql/generated-e2e-admin-types';
  4. import { createTestEnvironment } from '@vendure/testing';
  5. import fs from 'fs-extra';
  6. import gql from 'graphql-tag';
  7. import fetch from 'node-fetch';
  8. import path from 'path';
  9. import { initialData } from '../../../e2e-common/e2e-initial-data';
  10. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  11. import { AssetServerPlugin } from '../src/plugin';
  12. import {
  13. CreateAssetsMutation,
  14. DeleteAssetMutation,
  15. DeleteAssetMutationVariables,
  16. DeletionResult,
  17. } from './graphql/generated-e2e-asset-server-plugin-types';
  18. const TEST_ASSET_DIR = 'test-assets';
  19. const IMAGE_BASENAME = 'derick-david-409858-unsplash';
  20. describe('AssetServerPlugin', () => {
  21. let asset: AssetFragment;
  22. const sourceFilePath = path.join(__dirname, TEST_ASSET_DIR, `source/b6/${IMAGE_BASENAME}.jpg`);
  23. const previewFilePath = path.join(__dirname, TEST_ASSET_DIR, `preview/71/${IMAGE_BASENAME}__preview.jpg`);
  24. const { server, adminClient, shopClient } = createTestEnvironment(
  25. mergeConfig(testConfig(), {
  26. // logger: new DefaultLogger({ level: LogLevel.Info }),
  27. plugins: [
  28. AssetServerPlugin.init({
  29. assetUploadDir: path.join(__dirname, TEST_ASSET_DIR),
  30. route: 'assets',
  31. }),
  32. ],
  33. }),
  34. );
  35. beforeAll(async () => {
  36. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'source'));
  37. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'preview'));
  38. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'cache'));
  39. await server.init({
  40. initialData,
  41. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-empty.csv'),
  42. customerCount: 1,
  43. });
  44. await adminClient.asSuperAdmin();
  45. }, TEST_SETUP_TIMEOUT_MS);
  46. afterAll(async () => {
  47. await server.destroy();
  48. });
  49. it('names the Asset correctly', async () => {
  50. const filesToUpload = [path.join(__dirname, `fixtures/assets/${IMAGE_BASENAME}.jpg`)];
  51. const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({
  52. mutation: CREATE_ASSETS,
  53. filePaths: filesToUpload,
  54. mapVariables: filePaths => ({
  55. input: filePaths.map(p => ({ file: null })),
  56. }),
  57. });
  58. asset = createAssets[0] as AssetFragment;
  59. expect(asset.name).toBe(`${IMAGE_BASENAME}.jpg`);
  60. });
  61. it('creates the expected asset files', async () => {
  62. expect(fs.existsSync(sourceFilePath)).toBe(true);
  63. expect(fs.existsSync(previewFilePath)).toBe(true);
  64. });
  65. it('serves the source file', async () => {
  66. const res = await fetch(`${asset.source}`);
  67. const responseBuffer = await res.buffer();
  68. const sourceFile = await fs.readFile(sourceFilePath);
  69. expect(Buffer.compare(responseBuffer, sourceFile)).toBe(0);
  70. });
  71. it('serves the untransformed preview file', async () => {
  72. const res = await fetch(`${asset.preview}`);
  73. const responseBuffer = await res.buffer();
  74. const previewFile = await fs.readFile(previewFilePath);
  75. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  76. });
  77. it('can handle non-latin filenames', async () => {
  78. const FILE_NAME_ZH = '白飯';
  79. const filesToUpload = [path.join(__dirname, `fixtures/assets/${FILE_NAME_ZH}.jpg`)];
  80. const { createAssets }: { createAssets: AssetFragment[] } = await adminClient.fileUploadMutation({
  81. mutation: CREATE_ASSETS,
  82. filePaths: filesToUpload,
  83. mapVariables: filePaths => ({
  84. input: filePaths.map(p => ({ file: null })),
  85. }),
  86. });
  87. expect(createAssets[0].name).toBe(`${FILE_NAME_ZH}.jpg`);
  88. expect(createAssets[0].source).toContain(`${FILE_NAME_ZH}.jpg`);
  89. const previewUrl = encodeURI(`${createAssets[0].preview}`);
  90. const res = await fetch(previewUrl);
  91. expect(res.status).toBe(200);
  92. const previewFilePathZH = path.join(
  93. __dirname,
  94. TEST_ASSET_DIR,
  95. `preview/3f/${FILE_NAME_ZH}__preview.jpg`,
  96. );
  97. const responseBuffer = await res.buffer();
  98. const previewFile = await fs.readFile(previewFilePathZH);
  99. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  100. });
  101. describe('caching', () => {
  102. const cacheDir = path.join(__dirname, TEST_ASSET_DIR, 'cache');
  103. const cacheFileDir = path.join(__dirname, TEST_ASSET_DIR, 'cache', 'preview', '71');
  104. it('cache initially empty', async () => {
  105. const files = await fs.readdir(cacheDir);
  106. expect(files.length).toBe(0);
  107. });
  108. it('creates cached image on first request', async () => {
  109. const res = await fetch(`${asset.preview}?preset=thumb`);
  110. const responseBuffer = await res.buffer();
  111. expect(fs.existsSync(cacheFileDir)).toBe(true);
  112. const files = await fs.readdir(cacheFileDir);
  113. expect(files.length).toBe(1);
  114. expect(files[0]).toContain(`${IMAGE_BASENAME}__preview`);
  115. const cachedFile = await fs.readFile(path.join(cacheFileDir, files[0]));
  116. // was the file returned the exact same file as is stored in the cache dir?
  117. expect(Buffer.compare(responseBuffer, cachedFile)).toBe(0);
  118. });
  119. it('does not create a new cached image on a second request', async () => {
  120. const res = await fetch(`${asset.preview}?preset=thumb`);
  121. const files = await fs.readdir(cacheFileDir);
  122. expect(files.length).toBe(1);
  123. });
  124. it('does not create a new cached image for an untransformed image', async () => {
  125. const res = await fetch(`${asset.preview}`);
  126. const files = await fs.readdir(cacheFileDir);
  127. expect(files.length).toBe(1);
  128. });
  129. it('does not create a new cached image for an invalid preset', async () => {
  130. const res = await fetch(`${asset.preview}?preset=invalid`);
  131. const files = await fs.readdir(cacheFileDir);
  132. expect(files.length).toBe(1);
  133. const previewFile = await fs.readFile(previewFilePath);
  134. const responseBuffer = await res.buffer();
  135. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  136. });
  137. it('does not create a new cached image if cache=false', async () => {
  138. const res = await fetch(`${asset.preview}?preset=tiny&cache=false`);
  139. const files = await fs.readdir(cacheFileDir);
  140. expect(files.length).toBe(1);
  141. });
  142. it('creates a new cached image if cache=true', async () => {
  143. const res = await fetch(`${asset.preview}?preset=tiny&cache=true`);
  144. const files = await fs.readdir(cacheFileDir);
  145. expect(files.length).toBe(2);
  146. });
  147. });
  148. describe('unexpected input', () => {
  149. it('does not error on non-integer width', async () => {
  150. return fetch(`${asset.preview}?w=10.5`);
  151. });
  152. it('does not error on non-integer height', async () => {
  153. return fetch(`${asset.preview}?h=10.5`);
  154. });
  155. });
  156. describe('deletion', () => {
  157. it('deleting Asset deletes binary file', async () => {
  158. const { deleteAsset } = await adminClient.query<
  159. DeleteAssetMutation,
  160. DeleteAssetMutationVariables
  161. >(DELETE_ASSET, {
  162. input: {
  163. assetId: asset.id,
  164. force: true,
  165. },
  166. });
  167. expect(deleteAsset.result).toBe(DeletionResult.DELETED);
  168. expect(fs.existsSync(sourceFilePath)).toBe(false);
  169. expect(fs.existsSync(previewFilePath)).toBe(false);
  170. });
  171. });
  172. describe('MIME type detection', () => {
  173. let testImages: AssetFragment[] = [];
  174. async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) {
  175. const testImage = testImages.find(i => i.source.endsWith(ext))!;
  176. const result = await fetch(testImage.source);
  177. const contentType = result.headers.get('Content-Type');
  178. expect(contentType).toBe(expectedMimeType);
  179. }
  180. beforeAll(async () => {
  181. const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp'];
  182. const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`));
  183. const { createAssets }: CreateAssetsMutation = await adminClient.fileUploadMutation({
  184. mutation: CREATE_ASSETS,
  185. filePaths: filesToUpload,
  186. mapVariables: filePaths => ({
  187. input: filePaths.map(p => ({ file: null })),
  188. }),
  189. });
  190. testImages = createAssets as AssetFragment[];
  191. });
  192. it('gif', async () => {
  193. await testMimeTypeOfAssetWithExt('gif', 'image/gif');
  194. });
  195. it('jpg', async () => {
  196. await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg');
  197. });
  198. it('png', async () => {
  199. await testMimeTypeOfAssetWithExt('png', 'image/png');
  200. });
  201. it('svg', async () => {
  202. await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml');
  203. });
  204. it('tiff', async () => {
  205. await testMimeTypeOfAssetWithExt('tiff', 'image/tiff');
  206. });
  207. it('webp', async () => {
  208. await testMimeTypeOfAssetWithExt('webp', 'image/webp');
  209. });
  210. });
  211. // https://github.com/vendure-ecommerce/vendure/issues/1563
  212. it('falls back to binary preview if image file cannot be processed', async () => {
  213. const filesToUpload = [path.join(__dirname, `fixtures/assets/bad-image.jpg`)];
  214. const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({
  215. mutation: CREATE_ASSETS,
  216. filePaths: filesToUpload,
  217. mapVariables: filePaths => ({
  218. input: filePaths.map(p => ({ file: null })),
  219. }),
  220. });
  221. expect(createAssets.length).toBe(1);
  222. expect(createAssets[0].name).toBe('bad-image.jpg');
  223. });
  224. });
  225. export const CREATE_ASSETS = gql`
  226. mutation CreateAssets($input: [CreateAssetInput!]!) {
  227. createAssets(input: $input) {
  228. ... on Asset {
  229. id
  230. name
  231. source
  232. preview
  233. focalPoint {
  234. x
  235. y
  236. }
  237. }
  238. }
  239. }
  240. `;
  241. export const DELETE_ASSET = gql`
  242. mutation DeleteAsset($input: DeleteAssetInput!) {
  243. deleteAsset(input: $input) {
  244. result
  245. }
  246. }
  247. `;