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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. describe('caching', () => {
  72. const cacheDir = path.join(__dirname, TEST_ASSET_DIR, 'cache');
  73. const cacheFileDir = path.join(__dirname, TEST_ASSET_DIR, 'cache', 'preview', '71');
  74. it('cache initially empty', async () => {
  75. const files = await fs.readdir(cacheDir);
  76. expect(files.length).toBe(0);
  77. });
  78. it('creates cached image on first request', async () => {
  79. const res = await fetch(`${asset.preview}?preset=thumb`);
  80. const responseBuffer = await res.buffer();
  81. expect(fs.existsSync(cacheFileDir)).toBe(true);
  82. const files = await fs.readdir(cacheFileDir);
  83. expect(files.length).toBe(1);
  84. expect(files[0]).toContain(`${IMAGE_BASENAME}__preview`);
  85. const cachedFile = await fs.readFile(path.join(cacheFileDir, files[0]));
  86. // was the file returned the exact same file as is stored in the cache dir?
  87. expect(Buffer.compare(responseBuffer, cachedFile)).toBe(0);
  88. });
  89. it('does not create a new cached image on a second request', async () => {
  90. const res = await fetch(`${asset.preview}?preset=thumb`);
  91. const files = await fs.readdir(cacheFileDir);
  92. expect(files.length).toBe(1);
  93. });
  94. it('does not create a new cached image for an untransformed image', async () => {
  95. const res = await fetch(`${asset.preview}`);
  96. const files = await fs.readdir(cacheFileDir);
  97. expect(files.length).toBe(1);
  98. });
  99. it('does not create a new cached image for an invalid preset', async () => {
  100. const res = await fetch(`${asset.preview}?preset=invalid`);
  101. const files = await fs.readdir(cacheFileDir);
  102. expect(files.length).toBe(1);
  103. const previewFile = await fs.readFile(previewFilePath);
  104. const responseBuffer = await res.buffer();
  105. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  106. });
  107. it('does not create a new cached image if cache=false', async () => {
  108. const res = await fetch(`${asset.preview}?preset=tiny&cache=false`);
  109. const files = await fs.readdir(cacheFileDir);
  110. expect(files.length).toBe(1);
  111. });
  112. it('creates a new cached image if cache=true', async () => {
  113. const res = await fetch(`${asset.preview}?preset=tiny&cache=true`);
  114. const files = await fs.readdir(cacheFileDir);
  115. expect(files.length).toBe(2);
  116. });
  117. });
  118. describe('unexpected input', () => {
  119. it('does not error on non-integer width', async () => {
  120. return fetch(`${asset.preview}?w=10.5`);
  121. });
  122. it('does not error on non-integer height', async () => {
  123. return fetch(`${asset.preview}?h=10.5`);
  124. });
  125. });
  126. describe('deletion', () => {
  127. it('deleting Asset deletes binary file', async () => {
  128. const { deleteAsset } = await adminClient.query<DeleteAsset.Mutation, DeleteAsset.Variables>(
  129. DELETE_ASSET,
  130. {
  131. input: {
  132. assetId: asset.id,
  133. force: true,
  134. },
  135. },
  136. );
  137. expect(deleteAsset.result).toBe(DeletionResult.DELETED);
  138. expect(fs.existsSync(sourceFilePath)).toBe(false);
  139. expect(fs.existsSync(previewFilePath)).toBe(false);
  140. });
  141. });
  142. describe('MIME type detection', () => {
  143. let testImages: CreateAssets.CreateAssets[] = [];
  144. async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) {
  145. const testImage = testImages.find(i => i.source.endsWith(ext))!;
  146. const result = await fetch(testImage.source);
  147. const contentType = result.headers.get('Content-Type');
  148. expect(contentType).toBe(expectedMimeType);
  149. }
  150. beforeAll(async () => {
  151. const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp'];
  152. const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`));
  153. const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({
  154. mutation: CREATE_ASSETS,
  155. filePaths: filesToUpload,
  156. mapVariables: filePaths => ({
  157. input: filePaths.map(p => ({ file: null })),
  158. }),
  159. });
  160. testImages = createAssets;
  161. });
  162. it('gif', async () => {
  163. await testMimeTypeOfAssetWithExt('gif', 'image/gif');
  164. });
  165. it('jpg', async () => {
  166. await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg');
  167. });
  168. it('png', async () => {
  169. await testMimeTypeOfAssetWithExt('png', 'image/png');
  170. });
  171. it('svg', async () => {
  172. await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml');
  173. });
  174. it('tiff', async () => {
  175. await testMimeTypeOfAssetWithExt('tiff', 'image/tiff');
  176. });
  177. it('webp', async () => {
  178. await testMimeTypeOfAssetWithExt('webp', 'image/webp');
  179. });
  180. });
  181. });
  182. export const CREATE_ASSETS = gql`
  183. mutation CreateAssets($input: [CreateAssetInput!]!) {
  184. createAssets(input: $input) {
  185. ... on Asset {
  186. id
  187. name
  188. source
  189. preview
  190. focalPoint {
  191. x
  192. y
  193. }
  194. }
  195. }
  196. }
  197. `;
  198. export const DELETE_ASSET = gql`
  199. mutation DeleteAsset($input: DeleteAssetInput!) {
  200. deleteAsset(input: $input) {
  201. result
  202. }
  203. }
  204. `;