HATEOAS-first backend framework.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

480 lines
17 KiB

  1. import {IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, request, RequestOptions} from 'http';
  2. import {Method, DataSource} from '../src/backend';
  3. import {FALLBACK_LANGUAGE, Language} from '../src/common';
  4. interface ClientParams {
  5. method: Method;
  6. path: string;
  7. headers?: IncomingHttpHeaders;
  8. body?: unknown;
  9. }
  10. type ResponseBody = Buffer | string | object;
  11. export interface TestClient {
  12. (params: ClientParams): Promise<[IncomingMessage, ResponseBody?]>;
  13. acceptMediaType(mediaType: string): this;
  14. acceptLanguage(language: string): this;
  15. acceptCharset(charset: string): this;
  16. contentType(mediaType: string): this;
  17. contentCharset(charset: string): this;
  18. }
  19. export const createTestClient = (options: Omit<RequestOptions, 'method' | 'path'>): TestClient => {
  20. const additionalHeaders: OutgoingHttpHeaders = {};
  21. const client = (params: ClientParams) => new Promise<[IncomingMessage, ResponseBody?]>((resolve, reject) => {
  22. const {
  23. ...etcAdditionalHeaders
  24. } = additionalHeaders;
  25. // odd that request() uses OutgoingHttpHeaders instead of IncomingHttpHeaders...
  26. const headers: OutgoingHttpHeaders = {
  27. ...(options.headers ?? {}),
  28. ...etcAdditionalHeaders,
  29. };
  30. let contentTypeHeader: string | undefined;
  31. if (typeof params.body !== 'undefined') {
  32. contentTypeHeader = headers['content-type'] = params.headers?.['content-type'] ?? 'application/json';
  33. }
  34. const req = request({
  35. ...options,
  36. method: params.method,
  37. path: params.path,
  38. headers,
  39. });
  40. req.on('response', (res) => {
  41. // if (req.method.toUpperCase() === 'QUERY') {
  42. // res.statusMessage = '';
  43. // res.statusCode = 200;
  44. // }
  45. res.on('error', (err) => {
  46. reject(err);
  47. });
  48. let resBuffer: Buffer | undefined;
  49. res.on('data', (c) => {
  50. resBuffer = (
  51. typeof resBuffer === 'undefined'
  52. ? Buffer.from(c)
  53. : Buffer.concat([resBuffer, c])
  54. );
  55. });
  56. res.on('close', () => {
  57. const acceptHeader = Array.isArray(headers['accept']) ? headers['accept'].join('; ') : headers['accept'];
  58. const contentTypeBase = acceptHeader ?? 'application/octet-stream';
  59. const [type, subtype] = contentTypeBase.split('/');
  60. const allSubtypes = subtype.split('+');
  61. if (typeof resBuffer !== 'undefined') {
  62. if (allSubtypes.includes('json')) {
  63. const acceptCharset = (
  64. Array.isArray(headers['accept-charset'])
  65. ? headers['accept-charset'].join('; ')
  66. : headers['accept-charset']
  67. ) as BufferEncoding | undefined;
  68. resolve([res, JSON.parse(resBuffer.toString(acceptCharset ?? 'utf-8'))]);
  69. return;
  70. }
  71. if (type === 'text') {
  72. const acceptCharset = (
  73. Array.isArray(headers['accept-charset'])
  74. ? headers['accept-charset'].join('; ')
  75. : headers['accept-charset']
  76. ) as BufferEncoding | undefined;
  77. resolve([res, resBuffer.toString(acceptCharset ?? 'utf-8')]);
  78. return;
  79. }
  80. resolve([res, resBuffer]);
  81. return;
  82. }
  83. resolve([res]);
  84. });
  85. });
  86. req.on('error', (err) => {
  87. reject(err);
  88. })
  89. if (typeof params.body !== 'undefined') {
  90. const theContentTypeHeader = Array.isArray(contentTypeHeader) ? contentTypeHeader.join('; ') : contentTypeHeader?.toString();
  91. const contentTypeAll = theContentTypeHeader ?? 'application/octet-stream';
  92. const [contentTypeBase, ...contentTypeParams] = contentTypeAll.split(';').map((s) => s.replace(/\s+/g, '').trim());
  93. const charsetParam = contentTypeParams.find((s) => s.startsWith('charset='));
  94. const charset = charsetParam?.split('=')?.[1] as BufferEncoding | undefined;
  95. const [, subtype] = contentTypeBase.split('/');
  96. const allSubtypes = subtype.split('+');
  97. req.write(
  98. allSubtypes.includes('json')
  99. ? JSON.stringify(params.body)
  100. : Buffer.from(params.body?.toString() ?? '', contentTypeBase === 'text' ? charset : undefined)
  101. );
  102. }
  103. req.end();
  104. });
  105. client.acceptMediaType = function acceptMediaType(mediaType: string) {
  106. additionalHeaders['accept'] = mediaType;
  107. return this;
  108. };
  109. client.acceptLanguage = function acceptLanguage(language: string) {
  110. additionalHeaders['accept-language'] = language;
  111. return this;
  112. };
  113. client.acceptCharset = function acceptCharset(charset: string) {
  114. additionalHeaders['accept-charset'] = charset;
  115. return this;
  116. };
  117. client.contentType = function contentType(mediaType: string) {
  118. additionalHeaders['content-type'] = mediaType;
  119. return this;
  120. };
  121. client.contentCharset = function contentCharset(charset: string) {
  122. additionalHeaders['content-type'] = `${additionalHeaders['content-type']}; charset="${charset}"`;
  123. return this;
  124. };
  125. return client;
  126. };
  127. export const dummyGenerationStrategy = () => Promise.resolve();
  128. export class DummyError extends Error {}
  129. export class DummyDataSource implements DataSource {
  130. private resource?: { dataSource?: unknown };
  131. async create(): Promise<object> {
  132. return {};
  133. }
  134. async delete(): Promise<void> {}
  135. async emplace(): Promise<[object, boolean]> {
  136. return [{}, false];
  137. }
  138. async getById(): Promise<object> {
  139. return {};
  140. }
  141. async newId(): Promise<string> {
  142. return '';
  143. }
  144. async getMultiple(): Promise<object[]> {
  145. return [];
  146. }
  147. async getSingle(): Promise<object> {
  148. return {};
  149. }
  150. async getTotalCount(): Promise<number> {
  151. return 0;
  152. }
  153. async initialize(): Promise<void> {}
  154. async patch(): Promise<object> {
  155. return {};
  156. }
  157. prepareResource(rr: unknown) {
  158. this.resource = rr as unknown as { dataSource: DummyDataSource };
  159. this.resource.dataSource = this;
  160. }
  161. }
  162. export const TEST_LANGUAGE: Language = {
  163. name: FALLBACK_LANGUAGE.name,
  164. statusMessages: {
  165. resourceCollectionQueried: '$Resource Collection Queried',
  166. unableToSerializeResponse: 'Unable To Serialize Response',
  167. unableToEncodeResponse: 'Unable To Encode Response',
  168. unableToBindResourceDataSource: 'Unable To Bind $RESOURCE Data Source',
  169. unableToInitializeResourceDataSource: 'Unable To Initialize $RESOURCE Data Source',
  170. unableToFetchResourceCollection: 'Unable To Fetch $RESOURCE Collection',
  171. unableToFetchResource: 'Unable To Fetch $RESOURCE',
  172. unableToDeleteResource: 'Unable To Delete $RESOURCE',
  173. languageNotAcceptable: 'Language Not Acceptable',
  174. characterSetNotAcceptable: 'Character Set Not Acceptable',
  175. unableToDeserializeResource: 'Unable To Deserialize $RESOURCE',
  176. unableToDecodeResource: 'Unable To Decode $RESOURCE',
  177. mediaTypeNotAcceptable: 'Media Type Not Acceptable',
  178. methodNotAllowed: 'Method Not Allowed',
  179. urlNotFound: 'URL Not Found',
  180. badRequest: 'Bad Request',
  181. ok: 'OK',
  182. provideOptions: 'Provide Options',
  183. resourceCollectionFetched: '$RESOURCE Collection Fetched',
  184. resourceFetched: '$RESOURCE Fetched',
  185. resourceNotFound: '$RESOURCE Not Found',
  186. deleteNonExistingResource: 'Delete Non-Existing $RESOURCE',
  187. resourceDeleted: '$RESOURCE Deleted',
  188. unableToDeserializeRequest: 'Unable To Deserialize Request',
  189. patchNonExistingResource: 'Patch Non-Existing $RESOURCE',
  190. unableToPatchResource: 'Unable To Patch $RESOURCE',
  191. invalidResourcePatch: 'Invalid $RESOURCE Patch',
  192. invalidResourcePatchType: 'Invalid $RESOURCE Patch Type',
  193. invalidResource: 'Invalid $RESOURCE',
  194. resourcePatched: '$RESOURCE Patched',
  195. resourceCreated: '$RESOURCE Created',
  196. resourceReplaced: '$RESOURCE Replaced',
  197. unableToGenerateIdFromResourceDataSource: 'Unable To Generate ID From $RESOURCE Data Source',
  198. unableToAssignIdFromResourceDataSource: 'Unable To Assign ID From $RESOURCE Data Source',
  199. unableToEmplaceResource: 'Unable To Emplace $RESOURCE',
  200. resourceIdNotGiven: '$RESOURCE ID Not Given',
  201. unableToCreateResource: 'Unable To Create $RESOURCE',
  202. notImplemented: 'Not Implemented',
  203. internalServerError: 'Internal Server Error',
  204. },
  205. bodies: {
  206. badRequest: [
  207. 'An invalid request has been made.',
  208. [
  209. 'Check if the request body has all the required attributes for this endpoint.',
  210. 'Check if the request body has only the valid attributes for this endpoint.',
  211. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  212. 'Check if the request is appropriate for this endpoint.',
  213. ],
  214. ],
  215. languageNotAcceptable: [
  216. 'The server could not process a response suitable for the client\'s provided language requirement.',
  217. [
  218. 'Choose from the available languages on this service.',
  219. 'Contact the administrator to provide localization for the client\'s given requirements.',
  220. ],
  221. ],
  222. characterSetNotAcceptable: [
  223. 'The server could not process a response suitable for the client\'s provided character set requirement.',
  224. [
  225. 'Choose from the available character sets on this service.',
  226. 'Contact the administrator to provide localization for the client\'s given requirements.',
  227. ],
  228. ],
  229. mediaTypeNotAcceptable: [
  230. 'The server could not process a response suitable for the client\'s provided media type requirement.',
  231. [
  232. 'Choose from the available media types on this service.',
  233. 'Contact the administrator to provide localization for the client\'s given requirements.',
  234. ],
  235. ],
  236. deleteNonExistingResource: [
  237. 'The client has attempted to delete a resource that does not exist.',
  238. [
  239. 'Ensure that the resource still exists.',
  240. 'Ensure that the correct method is provided.',
  241. ],
  242. ],
  243. internalServerError: [
  244. 'An unknown error has occurred within the service.',
  245. [
  246. 'Try the request again at a later time.',
  247. 'Contact the administrator if the service remains in a degraded or non-functional state.',
  248. ],
  249. ],
  250. invalidResource: [
  251. 'The request has an invalid structure or is missing some attributes.',
  252. [
  253. 'Check if the request body has all the required attributes for this endpoint.',
  254. 'Check if the request body has only the valid attributes for this endpoint.',
  255. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  256. ],
  257. ],
  258. invalidResourcePatch: [
  259. 'The request has an invalid patch data.',
  260. [
  261. 'Check if the appropriate patch type is specified on the request data.',
  262. 'Check if the request body has all the required attributes for this endpoint.',
  263. 'Check if the request body has only the valid attributes for this endpoint.',
  264. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  265. ],
  266. ],
  267. invalidResourcePatchType: [
  268. 'The request has an invalid or unsupported kind of patch data.',
  269. [
  270. 'Check if the appropriate patch type is specified on the request data.',
  271. 'Check if the request body has all the required attributes for this endpoint.',
  272. 'Check if the request body has only the valid attributes for this endpoint.',
  273. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  274. ],
  275. ],
  276. methodNotAllowed: [
  277. 'A request with an invalid or unsupported method has been made.',
  278. [
  279. 'Check if the request method is appropriate for this endpoint.',
  280. 'Check if the client is authorized to perform the method on this endpoint.',
  281. ]
  282. ],
  283. notImplemented: [
  284. 'The service does not have any implementation for the accessed endpoint.',
  285. [
  286. 'Try the request again at a later time.',
  287. 'Contact the administrator if the service remains in a degraded or non-functional state.',
  288. ],
  289. ],
  290. patchNonExistingResource: [
  291. 'The client has attempted to patch a resource that does not exist.',
  292. [
  293. 'Ensure that the resource still exists.',
  294. 'Ensure that the correct method is provided.',
  295. ],
  296. ],
  297. resourceIdNotGiven: [
  298. 'The resource ID is not provided for the accessed endpoint.',
  299. [
  300. 'Check if the resource ID is provided and valid in the URL.',
  301. 'Check if the request method is appropriate for this endpoint.',
  302. ],
  303. ],
  304. unableToAssignIdFromResourceDataSource: [
  305. 'The resource could not be assigned an ID from the associated data source.',
  306. [
  307. 'Try the request again at a later time.',
  308. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  309. ],
  310. ],
  311. unableToBindResourceDataSource: [
  312. 'The resource could not be associated from the data source.',
  313. [
  314. 'Try the request again at a later time.',
  315. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  316. ],
  317. ],
  318. unableToCreateResource: [
  319. 'An error has occurred on creating the resource.',
  320. [
  321. 'Check if the request method is appropriate for this endpoint.',
  322. 'Check if the request body has all the required attributes for this endpoint.',
  323. 'Check if the request body has only the valid attributes for this endpoint.',
  324. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  325. 'Try the request again at a later time.',
  326. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  327. ],
  328. ],
  329. unableToDecodeResource: [
  330. 'The resource byte array could not be decoded for the provided character set.',
  331. [
  332. 'Choose from the available character sets on this service.',
  333. 'Contact the administrator to provide localization for the client\'s given requirements.',
  334. ],
  335. ],
  336. unableToDeleteResource: [
  337. 'An error has occurred on deleting the resource.',
  338. [
  339. 'Check if the request method is appropriate for this endpoint.',
  340. 'Try the request again at a later time.',
  341. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  342. ],
  343. ],
  344. unableToDeserializeRequest: [
  345. 'The decoded request byte array could not be deserialized for the provided media type.',
  346. [
  347. 'Choose from the available media types on this service.',
  348. 'Contact the administrator to provide localization for the client\'s given requirements.',
  349. ],
  350. ],
  351. unableToDeserializeResource: [
  352. 'The decoded resource could not be deserialized for the provided media type.',
  353. [
  354. 'Choose from the available media types on this service.',
  355. 'Contact the administrator to provide localization for the client\'s given requirements.',
  356. ],
  357. ],
  358. unableToEmplaceResource: [
  359. 'An error has occurred on emplacing the resource.',
  360. [
  361. 'Check if the request method is appropriate for this endpoint.',
  362. 'Check if the request body has all the required attributes for this endpoint.',
  363. 'Check if the request body has only the valid attributes for this endpoint.',
  364. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  365. 'Try the request again at a later time.',
  366. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  367. ],
  368. ],
  369. unableToEncodeResponse: [
  370. 'The response data could not be encoded for the provided character set.',
  371. [
  372. 'Choose from the available character sets on this service.',
  373. 'Contact the administrator to provide localization for the client\'s given requirements.',
  374. ],
  375. ],
  376. unableToFetchResource: [
  377. 'An error has occurred on fetching the resource.',
  378. [
  379. 'Check if the request method is appropriate for this endpoint.',
  380. 'Try the request again at a later time.',
  381. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  382. ],
  383. ],
  384. unableToFetchResourceCollection: [
  385. 'An error has occurred on fetching the resource collection.',
  386. [
  387. 'Check if the request method is appropriate for this endpoint.',
  388. 'Try the request again at a later time.',
  389. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  390. ],
  391. ],
  392. unableToGenerateIdFromResourceDataSource: [
  393. 'The associated data source for the resource could not produce an ID.',
  394. [
  395. 'Try the request again at a later time.',
  396. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  397. ],
  398. ],
  399. unableToInitializeResourceDataSource: [
  400. 'The associated data source for the resource could not be connected for usage.',
  401. [
  402. 'Try the request again at a later time.',
  403. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  404. ],
  405. ],
  406. unableToPatchResource: [
  407. 'An error has occurred on patching the resource.',
  408. [
  409. 'Check if the request method is appropriate for this endpoint.',
  410. 'Check if the request body has all the required attributes for this endpoint.',
  411. 'Check if the request body has only the valid attributes for this endpoint.',
  412. 'Check if the request body matches the schema for the resource associated with this endpoint.',
  413. 'Try the request again at a later time.',
  414. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  415. ],
  416. ],
  417. unableToSerializeResponse: [
  418. 'The response data could not be serialized for the provided media type.',
  419. [
  420. 'Choose from the available media types on this service.',
  421. 'Contact the administrator to provide localization for the client\'s given requirements.',
  422. ],
  423. ],
  424. urlNotFound: [
  425. 'An endpoint in the provided URL could not be found.',
  426. [
  427. 'Check if the request URL is correct.',
  428. 'Try the request again at a later time.',
  429. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  430. ],
  431. ],
  432. resourceNotFound: [
  433. 'The resource in the provided URL could not be found.',
  434. [
  435. 'Check if the request URL is correct.',
  436. 'Try the request again at a later time.',
  437. 'Contact the administrator regarding missing configuration or unavailability of dependencies.',
  438. ],
  439. ],
  440. },
  441. };