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

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