hooks.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { baseUrl, defaultFetchOpts } from "./constants";
  2. //#region validate objects
  3. /** Checks if the given object has the specified properties */
  4. export function checkObjProps(val: unknown, props: string[]) {
  5. expect(typeof val).toBe("object");
  6. for(const prop of props)
  7. expect(val).toHaveProperty(prop);
  8. }
  9. /** Checks if the given song object has the required properties */
  10. export function checkSongProps(songObj: unknown) {
  11. return checkObjProps(songObj, [
  12. "url",
  13. "path",
  14. "lyricsState",
  15. "id",
  16. "meta.title",
  17. "meta.fullTitle",
  18. "meta.artists",
  19. ]);
  20. }
  21. /** Checks if the given album object has the required properties */
  22. export function checkAlbumProps(albumObj: unknown) {
  23. return checkObjProps(albumObj, [
  24. "name",
  25. "fullTitle",
  26. "url",
  27. "coverArt",
  28. "id",
  29. "artist",
  30. ]);
  31. }
  32. /** Checks if the given artist object has the required properties */
  33. export function checkArtistProps(artistObj: unknown) {
  34. return checkObjProps(artistObj, [
  35. "name",
  36. "url",
  37. "image",
  38. "headerImage",
  39. ]);
  40. }
  41. /** Checks if the given translation object has the required properties */
  42. export function checkTranslationProps(translationObj: unknown) {
  43. return checkObjProps(translationObj, [
  44. "language",
  45. "id",
  46. "path",
  47. "title",
  48. "url",
  49. ]);
  50. }
  51. //#region send requests
  52. /** Sends a request to the specified URL with the given options. Authentication and method "GET" are set by default. */
  53. export async function sendReq<
  54. TAsJson extends boolean,
  55. >(
  56. path: string,
  57. opts?: RequestInit & { asJson?: TAsJson },
  58. ): Promise<{
  59. res: Response;
  60. status: number;
  61. headers: Headers;
  62. }> {
  63. const res = await fetch(`${baseUrl}/${path.startsWith("/") ? path.substring(1) : path}`, { ...defaultFetchOpts, ...opts });
  64. return { res, status: res.status, headers: res.headers };
  65. }