Files
directus/api/src/utils/get-cache-key.test.ts
Rijk van Zanten 2983e61870 The Great TypeScript Modernization Program Season 3 Episode 6: The Big One (#18014)
* Step 1

* Step 2

* False sense of confidence

* Couple more before dinner

* Update schema package

* Update format-title

* Upgrade specs file

* Close

* Replace ts-node-dev with tsx, and various others

* Replace lodash with lodash-es

* Add lodash-es types

* Update knex import

* More fun is had

* FSE

* Consolidate repos

* Various tweaks and fixes

* Fix specs

* Remove dependency on knex-schema-inspector

* Fix wrong imports of inspector

* Move shared exceptions to new package

* Move constants to separate module

* Move types to new types package

* Use directus/types

* I believe this is no longer needed

* [WIP] Start moving utils to esm

* ESMify Shared

* Move shared utils to  @directus/utils

* Use @directus/utils instead of @directus/shared/utils

* It runs!

* Use correct schemaoverview type

* Fix imports

* Fix the thing

* Start on new update-checker lib

* Use new update-check package

* Swap out directus/shared in app

* Pushing through the last bits now

* Dangerously make extensions SDK ESM

* Use @directus/types in tests

* Copy util function to test

* Fix linter config

* Add missing import

* Hot takes

* Fix build

* Curse these default exports

* No tests in constants

* Add tests

* Remove tests from types

* Add tests for exceptions

* Fix test

* Fix app tests

* Fix import in test

* Fix various tests

* Fix specs export

* Some more tests

* Remove broken integration tests

These were broken beyond repair.. They were also written before we really knew what we we're doing with tests, so I think it's better to say goodbye and start over with these

* Regenerate lockfile

* Fix imports from merge

* I create my own problems

* Make sharp play nice

* Add vitest config

* Install missing blackbox dep

* Consts shouldn't be in types

tsk tsk tsk tsk

* Fix type/const usage in extensions-sdk

* cursed.default

* Reduce circular deps

* Fix circular dep in items service

* vvv

* Trigger testing for all vendors

* Add workaround for rollup

* Prepend the file protocol for the ESM loader to be compatible with Windows
"WARN: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'"

* Fix postgres

* Schema package updates

Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com>

* Resolve cjs/mjs extensions

* Clean-up eslint config

* fixed extension concatination

* using string interpolation for consistency

* Revert MySQL optimisation

* Revert testing for all vendors

* Replace tsx with esbuild-kit/esm-loader

Is a bit faster and we can rely on the built-in `watch` and `inspect`
functionalities of Node.js

Note: The possibility to watch other files (.env in our case) might be
added in the future, see https://github.com/nodejs/node/issues/45467

* Use exact version for esbuild-kit/esm-loader

* Fix import

---------

Co-authored-by: ian <licitdev@gmail.com>
Co-authored-by: Brainslug <tim@brainslug.nl>
Co-authored-by: Azri Kahar <42867097+azrikahar@users.noreply.github.com>
Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
2023-04-04 17:41:56 -04:00

110 lines
4.2 KiB
TypeScript

import type { Request } from 'express';
import { afterEach, beforeAll, describe, expect, SpyInstance, test, vi } from 'vitest';
import { getCacheKey } from './get-cache-key.js';
import * as getGraphqlQueryUtil from './get-graphql-query-and-variables.js';
const baseUrl = 'http://localhost';
const restUrl = `${baseUrl}/items/example`;
const graphQlUrl = `${baseUrl}/graphql`;
const accountability = { user: '00000000-0000-0000-0000-000000000000' };
const method = 'GET';
const requests = [
{
name: 'as unauthenticated request',
params: { method, originalUrl: restUrl },
key: '17da8272c9a0ec6eea38a37d6d78bddeb7c79045',
},
{
name: 'as authenticated request',
params: { method, originalUrl: restUrl, accountability },
key: '99a6394222a3d7d149ac1662fc2fff506932db58',
},
{
name: 'a request with a fields query',
params: { method, originalUrl: restUrl, sanitizedQuery: { fields: ['id', 'name'] } },
key: 'aa6e2d8a78de4dfb4af6eaa230d1cd9b7d31ed19',
},
{
name: 'a request with a filter query',
params: { method, originalUrl: restUrl, sanitizedQuery: { filter: { name: { _eq: 'test' } } } },
key: 'd7eb8970f0429e1cf85e12eb5bb8669f618b09d3',
},
{
name: 'a GraphQL GET query request',
params: { method, originalUrl: graphQlUrl, query: { query: 'query { test { id } }' } },
key: '201731b75c627c60554512d819b6935b54c73814',
},
{
name: 'a GraphQL POST query request',
params: { method: 'POST', originalUrl: graphQlUrl, body: { query: 'query { test { name } }' } },
key: '64eb0c48ea69d0863ff930398f29b5c7884f88f7',
},
{
name: 'an authenticated GraphQL GET query request',
params: { method, originalUrl: graphQlUrl, accountability, query: { query: 'query { test { id } }' } },
key: '9bc52c98dcf2de04c64589f52e0ada1e38d53a90',
},
{
name: 'an authenticated GraphQL POST query request',
params: { method: 'POST', originalUrl: graphQlUrl, accountability, body: { query: 'query { test { name } }' } },
key: '051ea77ce5ba71bbc88bcb567b9ddc602b585c13',
},
];
const cases = requests.map(({ name, params, key }) => [name, params, key]);
afterEach(() => {
vi.clearAllMocks();
});
describe('get cache key', () => {
describe('isGraphQl', () => {
let getGraphqlQuerySpy: SpyInstance;
beforeAll(() => {
getGraphqlQuerySpy = vi.spyOn(getGraphqlQueryUtil, 'getGraphqlQueryAndVariables');
});
test.each(['/items/test', '/items/graphql', '/collections/test', '/collections/graphql'])(
'path "%s" should not be interpreted as a graphql query',
(path) => {
getCacheKey({ originalUrl: `${baseUrl}${path}` } as Request);
expect(getGraphqlQuerySpy).not.toHaveBeenCalled();
}
);
test.each(['/graphql', '/graphql/system'])('path "%s" should be interpreted as a graphql query', (path) => {
getCacheKey({ originalUrl: `${baseUrl}${path}` } as Request);
expect(getGraphqlQuerySpy).toHaveBeenCalledOnce();
});
});
test.each(cases)('should create a cache key for %s', (_, params, key) => {
expect(getCacheKey(params as unknown as Request)).toEqual(key);
});
test('should create a unique key for each request', () => {
const keys = cases.map(([, params]) => getCacheKey(params as unknown as Request));
const hasDuplicate = keys.some((key) => keys.indexOf(key) !== keys.lastIndexOf(key));
expect(hasDuplicate).toBeFalsy();
});
test('should create a unique key for GraphQL requests with different variables', () => {
const query = 'query Test ($name: String) { test (filter: { name: { _eq: $name } }) { id } }';
const operationName = 'test';
const variables1 = JSON.stringify({ name: 'test 1' });
const variables2 = JSON.stringify({ name: 'test 2' });
const req1: any = { method, originalUrl: graphQlUrl, query: { query, operationName, variables: variables1 } };
const req2: any = { method, originalUrl: graphQlUrl, query: { query, operationName, variables: variables2 } };
const postReq1: any = { method: 'POST', originalUrl: req1.originalUrl, body: req1.query };
const postReq2: any = { method: 'POST', originalUrl: req2.originalUrl, body: req2.query };
expect(getCacheKey(req1)).not.toEqual(getCacheKey(req2));
expect(getCacheKey(postReq1)).not.toEqual(getCacheKey(postReq2));
expect(getCacheKey(req1)).toEqual(getCacheKey(postReq1));
expect(getCacheKey(req2)).toEqual(getCacheKey(postReq2));
});
});