made a request to get assignments

This commit is contained in:
2024-08-21 11:48:56 -06:00
parent 048473070e
commit 556c7a7372
4 changed files with 97 additions and 22 deletions

View File

@@ -1,9 +1,14 @@
import { canvasAssignmentService } from "@/services/canvas/canvasAssignmentService";
import Image from "next/image";
export default function Home() {
export default async function Home() {
const assignments = await canvasAssignmentService.getAll(960410);
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
{assignments.map((assignment) => (
<div key={assignment.id}>{assignment.name}</div>
))}
</main>
);
}

View File

@@ -0,0 +1,18 @@
import { CanvasAssignment } from "@/models/canvas/assignments/canvasAssignment";
import { canvasServiceUtils } from "./canvasServiceUtils";
export const canvasAssignmentService = {
async getAll(courseId: number): Promise<CanvasAssignment[]> {
const url = `courses/${courseId}/assignments`;
const assignments = await canvasServiceUtils.paginatedRequest<
CanvasAssignment[]
>({ url });
return assignments.flatMap((assignments) =>
assignments.map((a) => ({
...a,
due_at: a.due_at ? new Date(a.due_at).toLocaleString() : undefined, // timezones?
lock_at: a.lock_at ? new Date(a.lock_at).toLocaleString() : undefined, // timezones?
}))
);
},
};

View File

@@ -0,0 +1,59 @@
// services/canvasServiceUtils.ts
import { webRequestor } from "./webRequestor";
const BASE_URL = "https://snow.instructure.com/api/v1/";
const getNextUrl = (headers: Headers): string | undefined => {
const linkHeader = headers.get("Link");
if (!linkHeader) return undefined;
const links = linkHeader.split(",").map((link) => link.trim());
const nextLink = links.find((link) => link.includes('rel="next"'));
if (!nextLink) return undefined;
const nextUrl = nextLink.split(";")[0].trim().slice(1, -1);
return nextUrl.replace(BASE_URL, "").trim();
};
export const canvasServiceUtils = {
async paginatedRequest<T>(request: { url: string }): Promise<T[]> {
var requestCount = 1;
const url = new URL(request.url!, BASE_URL);
url.searchParams.set("per_page", "100");
const [firstData, firstResponse] = await webRequestor.get<T>(
url.toString()
);
if (!firstResponse.ok) {
console.error(
"error in response",
firstResponse.statusText,
firstResponse.body
);
throw new Error("error in response");
}
var returnData: T[] = firstData ? [firstData] : [];
var nextUrl = getNextUrl(firstResponse.headers);
while (nextUrl) {
requestCount += 1;
const [data, response] = await webRequestor.get<T>(nextUrl);
if (data) {
returnData = [...returnData, data];
}
nextUrl = getNextUrl(response.headers);
}
if (requestCount > 1) {
console.log(
`Requesting ${typeof returnData} took ${requestCount} requests`
);
}
return returnData;
},
};

View File

@@ -1,4 +1,3 @@
type FetchOptions = Omit<RequestInit, "method">;
const token = process.env.CANVAS_TOKEN;
@@ -20,7 +19,7 @@ const isRateLimited = async (response: Response): Promise<boolean> => {
);
};
const deserialize = async <T>(response: Response): Promise<T | null> => {
const deserialize = async <T>(response: Response): Promise<T | undefined> => {
if (!response.ok) {
console.error(`Error with response to ${response.url} ${response.status}`);
throw new Error(
@@ -112,11 +111,11 @@ const recursiveDeleteAsync = async (
throw e;
}
};
export const WebRequestor = {
getManyAsync: async <T>(
export const webRequestor = {
getMany: async <T>(
url: string,
options: FetchOptions = {}
): Promise<[T[] | null, Response]> => {
): Promise<[T[] | undefined, Response]> => {
const response = await fetch(url, {
...options,
method: "GET",
@@ -128,10 +127,10 @@ export const WebRequestor = {
return [await deserialize<T[]>(response), response];
},
getAsync: async <T>(
get: async <T>(
url: string,
options: FetchOptions = {}
): Promise<[T | null, Response]> => {
): Promise<[T | undefined, Response]> => {
const response = await fetch(url, {
...options,
method: "GET",
@@ -143,25 +142,19 @@ export const WebRequestor = {
return [await deserialize<T>(response), response];
},
postAsync: async (
url: string,
options: FetchOptions = {}
): Promise<Response> => {
post: async (url: string, options: FetchOptions = {}): Promise<Response> => {
return await rateLimitAwarePostAsync(url, options);
},
postAsyncWithDeserialize: async <T>(
postWithDeserialize: async <T>(
url: string,
options: FetchOptions = {}
): Promise<[T | null, Response]> => {
): Promise<[T | undefined, Response]> => {
const response = await rateLimitAwarePostAsync(url, options);
return [await deserialize<T>(response), response];
},
putAsync: async (
url: string,
options: FetchOptions = {}
): Promise<Response> => {
put: async (url: string, options: FetchOptions = {}): Promise<Response> => {
const response = await fetch(url, {
...options,
method: "PUT",
@@ -174,10 +167,10 @@ export const WebRequestor = {
return response;
},
putAsyncWithDeserialize: async <T>(
putWithDeserialize: async <T>(
url: string,
options: FetchOptions = {}
): Promise<[T | null, Response]> => {
): Promise<[T | undefined, Response]> => {
const response = await fetch(url, {
...options,
method: "PUT",
@@ -190,7 +183,7 @@ export const WebRequestor = {
return [await deserialize<T>(response), response];
},
deleteAsync: async (
delete: async (
url: string,
options: FetchOptions = {}
): Promise<Response> => {