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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. apiOptions: {
  21. port: 5050,
  22. },
  23. logger: new DefaultLogger({ level: LogLevel.Info }),
  24. plugins: [
  25. AssetServerPlugin.init({
  26. port: 3060,
  27. assetUploadDir: path.join(__dirname, TEST_ASSET_DIR),
  28. route: 'assets',
  29. }),
  30. ],
  31. }),
  32. );
  33. beforeAll(async () => {
  34. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'source'));
  35. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'preview'));
  36. await fs.emptyDir(path.join(__dirname, TEST_ASSET_DIR, 'cache'));
  37. await server.init({
  38. initialData,
  39. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-empty.csv'),
  40. customerCount: 1,
  41. });
  42. await adminClient.asSuperAdmin();
  43. }, TEST_SETUP_TIMEOUT_MS);
  44. afterAll(async () => {
  45. await server.destroy();
  46. });
  47. it('names the Asset correctly', async () => {
  48. const filesToUpload = [path.join(__dirname, `fixtures/assets/${IMAGE_BASENAME}.jpg`)];
  49. const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({
  50. mutation: CREATE_ASSETS,
  51. filePaths: filesToUpload,
  52. mapVariables: filePaths => ({
  53. input: filePaths.map(p => ({ file: null })),
  54. }),
  55. });
  56. expect(createAssets[0].name).toBe(`${IMAGE_BASENAME}.jpg`);
  57. asset = createAssets[0];
  58. });
  59. it('creates the expected asset files', async () => {
  60. expect(fs.existsSync(sourceFilePath)).toBe(true);
  61. expect(fs.existsSync(previewFilePath)).toBe(true);
  62. });
  63. it('serves the source file', async () => {
  64. const res = await fetch(`${asset.source}`);
  65. const responseBuffer = await res.buffer();
  66. const sourceFile = await fs.readFile(sourceFilePath);
  67. expect(Buffer.compare(responseBuffer, sourceFile)).toBe(0);
  68. });
  69. it('serves the untransformed preview file', async () => {
  70. const res = await fetch(`${asset.preview}`);
  71. const responseBuffer = await res.buffer();
  72. const previewFile = await fs.readFile(previewFilePath);
  73. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  74. });
  75. describe('caching', () => {
  76. const cacheDir = path.join(__dirname, TEST_ASSET_DIR, 'cache');
  77. const cacheFileDir = path.join(__dirname, TEST_ASSET_DIR, 'cache', 'preview', '71');
  78. it('cache initially empty', async () => {
  79. const files = await fs.readdir(cacheDir);
  80. expect(files.length).toBe(0);
  81. });
  82. it('creates cached image on first request', async () => {
  83. const res = await fetch(`${asset.preview}?preset=thumb`);
  84. const responseBuffer = await res.buffer();
  85. expect(fs.existsSync(cacheFileDir)).toBe(true);
  86. const files = await fs.readdir(cacheFileDir);
  87. expect(files.length).toBe(1);
  88. expect(files[0]).toContain(`${IMAGE_BASENAME}__preview`);
  89. const cachedFile = await fs.readFile(path.join(cacheFileDir, files[0]));
  90. // was the file returned the exact same file as is stored in the cache dir?
  91. expect(Buffer.compare(responseBuffer, cachedFile)).toBe(0);
  92. });
  93. it('does not create a new cached image on a second request', async () => {
  94. const res = await fetch(`${asset.preview}?preset=thumb`);
  95. const files = await fs.readdir(cacheFileDir);
  96. expect(files.length).toBe(1);
  97. });
  98. it('does not create a new cached image for an untransformed image', async () => {
  99. const res = await fetch(`${asset.preview}`);
  100. const files = await fs.readdir(cacheFileDir);
  101. expect(files.length).toBe(1);
  102. });
  103. it('does not create a new cached image for an invalid preset', async () => {
  104. const res = await fetch(`${asset.preview}?preset=invalid`);
  105. const files = await fs.readdir(cacheFileDir);
  106. expect(files.length).toBe(1);
  107. const previewFile = await fs.readFile(previewFilePath);
  108. const responseBuffer = await res.buffer();
  109. expect(Buffer.compare(responseBuffer, previewFile)).toBe(0);
  110. });
  111. it('does not create a new cached image if cache=false', async () => {
  112. const res = await fetch(`${asset.preview}?preset=tiny&cache=false`);
  113. const files = await fs.readdir(cacheFileDir);
  114. expect(files.length).toBe(1);
  115. });
  116. it('creates a new cached image if cache=true', async () => {
  117. const res = await fetch(`${asset.preview}?preset=tiny&cache=true`);
  118. const files = await fs.readdir(cacheFileDir);
  119. expect(files.length).toBe(2);
  120. });
  121. });
  122. describe('unexpected input', () => {
  123. it('does not error on non-integer width', async () => {
  124. return fetch(`${asset.preview}?w=10.5`);
  125. });
  126. it('does not error on non-integer height', async () => {
  127. return fetch(`${asset.preview}?h=10.5`);
  128. });
  129. });
  130. describe('deletion', () => {
  131. it('deleting Asset deletes binary file', async () => {
  132. const { deleteAsset } = await adminClient.query<DeleteAsset.Mutation, DeleteAsset.Variables>(
  133. DELETE_ASSET,
  134. {
  135. input: {
  136. assetId: asset.id,
  137. force: true,
  138. },
  139. },
  140. );
  141. expect(deleteAsset.result).toBe(DeletionResult.DELETED);
  142. expect(fs.existsSync(sourceFilePath)).toBe(false);
  143. expect(fs.existsSync(previewFilePath)).toBe(false);
  144. });
  145. });
  146. describe('MIME type detection', () => {
  147. let testImages: CreateAssets.CreateAssets[] = [];
  148. async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) {
  149. const testImage = testImages.find(i => i.source.endsWith(ext))!;
  150. const result = await fetch(testImage.source);
  151. const contentType = result.headers.get('Content-Type');
  152. expect(contentType).toBe(expectedMimeType);
  153. }
  154. beforeAll(async () => {
  155. const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp'];
  156. const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`));
  157. const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({
  158. mutation: CREATE_ASSETS,
  159. filePaths: filesToUpload,
  160. mapVariables: filePaths => ({
  161. input: filePaths.map(p => ({ file: null })),
  162. }),
  163. });
  164. testImages = createAssets;
  165. });
  166. it('gif', async () => {
  167. await testMimeTypeOfAssetWithExt('gif', 'image/gif');
  168. });
  169. it('jpg', async () => {
  170. await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg');
  171. });
  172. it('png', async () => {
  173. await testMimeTypeOfAssetWithExt('png', 'image/png');
  174. });
  175. it('svg', async () => {
  176. await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml');
  177. });
  178. it('tiff', async () => {
  179. await testMimeTypeOfAssetWithExt('tiff', 'image/tiff');
  180. });
  181. it('webp', async () => {
  182. await testMimeTypeOfAssetWithExt('webp', 'image/webp');
  183. });
  184. });
  185. });
  186. export const CREATE_ASSETS = gql`
  187. mutation CreateAssets($input: [CreateAssetInput!]!) {
  188. createAssets(input: $input) {
  189. ... on Asset {
  190. id
  191. name
  192. source
  193. preview
  194. focalPoint {
  195. x
  196. y
  197. }
  198. }
  199. }
  200. }
  201. `;
  202. export const DELETE_ASSET = gql`
  203. mutation DeleteAsset($input: DeleteAssetInput!) {
  204. deleteAsset(input: $input) {
  205. result
  206. }
  207. }
  208. `;