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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. 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. input: {
  141. assetId: asset.id,
  142. force: true,
  143. },
  144. },
  145. );
  146. expect(deleteAsset.result).toBe(DeletionResult.DELETED);
  147. expect(fs.existsSync(sourceFilePath)).toBe(false);
  148. expect(fs.existsSync(previewFilePath)).toBe(false);
  149. });
  150. });
  151. describe('MIME type detection', () => {
  152. let testImages: CreateAssets.CreateAssets[] = [];
  153. async function testMimeTypeOfAssetWithExt(ext: string, expectedMimeType: string) {
  154. const testImage = testImages.find(i => i.source.endsWith(ext))!;
  155. const result = await fetch(testImage.source);
  156. const contentType = result.headers.get('Content-Type');
  157. expect(contentType).toBe(expectedMimeType);
  158. }
  159. beforeAll(async () => {
  160. const formats = ['gif', 'jpg', 'png', 'svg', 'tiff', 'webp'];
  161. const filesToUpload = formats.map(ext => path.join(__dirname, `fixtures/assets/test.${ext}`));
  162. const { createAssets }: CreateAssets.Mutation = await adminClient.fileUploadMutation({
  163. mutation: CREATE_ASSETS,
  164. filePaths: filesToUpload,
  165. mapVariables: filePaths => ({
  166. input: filePaths.map(p => ({ file: null })),
  167. }),
  168. });
  169. testImages = createAssets;
  170. });
  171. it('gif', async () => {
  172. await testMimeTypeOfAssetWithExt('gif', 'image/gif');
  173. });
  174. it('jpg', async () => {
  175. await testMimeTypeOfAssetWithExt('jpg', 'image/jpeg');
  176. });
  177. it('png', async () => {
  178. await testMimeTypeOfAssetWithExt('png', 'image/png');
  179. });
  180. it('svg', async () => {
  181. await testMimeTypeOfAssetWithExt('svg', 'image/svg+xml');
  182. });
  183. it('tiff', async () => {
  184. await testMimeTypeOfAssetWithExt('tiff', 'image/tiff');
  185. });
  186. it('webp', async () => {
  187. await testMimeTypeOfAssetWithExt('webp', 'image/webp');
  188. });
  189. });
  190. });
  191. export const CREATE_ASSETS = gql`
  192. mutation CreateAssets($input: [CreateAssetInput!]!) {
  193. createAssets(input: $input) {
  194. ... on Asset {
  195. id
  196. name
  197. source
  198. preview
  199. focalPoint {
  200. x
  201. y
  202. }
  203. }
  204. }
  205. }
  206. `;
  207. export const DELETE_ASSET = gql`
  208. mutation DeleteAsset($input: DeleteAssetInput!) {
  209. deleteAsset(input: $input) {
  210. result
  211. }
  212. }
  213. `;