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

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