FPSMS-frontend
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.
 
 

169 lines
4.7 KiB

  1. import { SessionWithTokens, authOptions } from "@/config/authConfig";
  2. import { getServerSession } from "next-auth";
  3. import { headers } from "next/headers";
  4. import { redirect } from "next/navigation";
  5. export interface Pageable {
  6. pageSize?: number;
  7. pageNum?: number;
  8. }
  9. export type SearchParams = {
  10. searchParams: { [key: string]: string | string[] | undefined };
  11. };
  12. export interface searchParamsProps {
  13. searchParams: { [key: string]: string | string[] | undefined };
  14. }
  15. export class ServerFetchError extends Error {
  16. public readonly response: Response | undefined;
  17. constructor(message?: string, response?: Response) {
  18. super(message);
  19. this.response = response;
  20. Object.setPrototypeOf(this, ServerFetchError.prototype);
  21. }
  22. }
  23. export async function serverFetchWithNoContent(...args: FetchParams) {
  24. const response = await serverFetch(...args);
  25. if (response.ok) {
  26. return response.status; // 204 No Content, e.g. for delete data
  27. } else {
  28. switch (response.status) {
  29. case 401:
  30. signOutUser();
  31. default:
  32. console.error(await response.text());
  33. throw Error("Something went wrong fetching data in server.");
  34. }
  35. }
  36. }
  37. export const serverFetch: typeof fetch = async (input, init) => {
  38. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  39. const session = await getServerSession<any, SessionWithTokens>(authOptions);
  40. const accessToken = session?.accessToken;
  41. return fetch(input, {
  42. ...init,
  43. headers: {
  44. ...init?.headers,
  45. ...(accessToken
  46. ? {
  47. Authorization: `Bearer ${accessToken}`,
  48. Accept:
  49. "application/json, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, multipart/form-data",
  50. }
  51. : {}),
  52. },
  53. });
  54. };
  55. type FetchParams = Parameters<typeof fetch>;
  56. export async function serverFetchJson<T>(...args: FetchParams) {
  57. const response = await serverFetch(...args);
  58. console.log(response.status);
  59. if (response.ok) {
  60. if (response.status === 204) {
  61. return response.status as T;
  62. }
  63. return response.json() as T;
  64. } else {
  65. switch (response.status) {
  66. case 401:
  67. signOutUser();
  68. default:
  69. throw new ServerFetchError(
  70. "Something went wrong fetching data in server.",
  71. response,
  72. );
  73. }
  74. }
  75. }
  76. export async function serverFetchBlob<T>(...args: FetchParams) {
  77. const response = await serverFetch(...args);
  78. if (response.ok) {
  79. const body = response.body;
  80. // console.log(body)
  81. // console.log(body?.tee()[0].getReader())
  82. const reader = body?.getReader();
  83. let finalUInt8Array = new Uint8Array();
  84. let done = false;
  85. while (!done) {
  86. const read = await reader?.read();
  87. // version 1
  88. if (read?.done) {
  89. done = true;
  90. } else {
  91. const tempUInt8Array = new Uint8Array(
  92. finalUInt8Array.length + read?.value.length!,
  93. );
  94. tempUInt8Array.set(finalUInt8Array);
  95. tempUInt8Array.set(read?.value!, finalUInt8Array.length);
  96. finalUInt8Array = new Uint8Array(tempUInt8Array.length!);
  97. finalUInt8Array.set(tempUInt8Array);
  98. // console.log("1", finalUInt8Array)
  99. }
  100. }
  101. // version 2 & return bodyRead
  102. // const bodyRead = reader?.read().then(function processText({ done, value }): any {
  103. // // Result objects contain two properties:
  104. // // done - true if the stream has already given you all its data.
  105. // // value - some data. Always undefined when done is true.
  106. // if (done) {
  107. // console.log("Stream complete");
  108. // return { filename: response.headers.get("filename"), blobValue: finalUInt8Array } as T;;
  109. // }
  110. // // value for fetch streams is a Uint8Array
  111. // finalUInt8Array = new Uint8Array(value.length)
  112. // finalUInt8Array.set(value)
  113. // console.log(finalUInt8Array)
  114. // // Read some more, and call this function again
  115. // return reader.read().then(processText);
  116. // })
  117. // const bodyValue = bodyRead?.value
  118. // const blob = await response.blob()
  119. // const blobText = await blob.text();
  120. // const blobType = await blob.type;
  121. // console.log(bodyReader)
  122. // console.log("2", finalUInt8Array)
  123. // console.log(bodyValue)
  124. return {
  125. filename: response.headers.get("filename"),
  126. blobValue: finalUInt8Array,
  127. } as T;
  128. } else {
  129. switch (response.status) {
  130. case 401:
  131. signOutUser();
  132. default:
  133. console.error(await response.text());
  134. throw Error("Something went wrong fetching data in server.");
  135. }
  136. }
  137. }
  138. export const signOutUser = () => {
  139. const headersList = headers();
  140. const referer = headersList.get("referer");
  141. redirect(
  142. `/logout${referer ? `?callbackUrl=${encodeURIComponent(referer)}` : ""}`,
  143. );
  144. };