FPSMS-frontend
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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