Skip to content
This repository has been archived by the owner on Jun 1, 2024. It is now read-only.

Commit

Permalink
Refactor the rest of the api functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Adamv27 authored and hcientist committed Jun 1, 2024
1 parent 7e1a1e2 commit 82ef29b
Showing 1 changed file with 89 additions and 202 deletions.
291 changes: 89 additions & 202 deletions api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-restricted-syntax */
import { getSession } from 'next-auth/react';

// https://allover.twodee.org/remote-state/fetching-memories/
function assertResponse(response) {
if (response.status >= 200 && response.status < 300) {
Expand All @@ -8,14 +9,13 @@ function assertResponse(response) {
throw new Error(`${response.status}: ${response.statusText}`);
}


async function getDjangoToken() {
const session = await getSession();
if (!session || !session.djangoToken) return;
return session.djangoToken
}

async function makeRequest(url, method="GET", body=null, headers={}) {
async function makeRequest(endpoint, method="GET", body=null, headers={}) {
const token = await getDjangoToken();
if (!token) return {};

Expand All @@ -26,7 +26,7 @@ async function makeRequest(url, method="GET", body=null, headers={}) {
}

const API = `${process.env.NEXT_PUBLIC_BACKEND_HOST}/api`;
url = `${API}/${url}`
const url = `${API}/${endpoint}`

const response = await fetch(url, {
method,
Expand All @@ -40,236 +40,123 @@ async function makeRequest(url, method="GET", body=null, headers={}) {
return data;
}


export async function getEnrollments() {
const url = "enrollments/";
const json = await makeRequest(url);
const endpoint = "enrollments/";
const json = await makeRequest(endpoint);
return json;
}


export function getStudentAssignments(slug) {
return async () => {
const url = `courses/${slug}/assignments/`;
const json = await makeRequest(url);
const endpoint = `courses/${slug}/assignments/`;
const json = await makeRequest(endpoint);
return json
}
}

export function getAllPieces(courseSlug) {
return () =>
getSession().then((session) => {
const token = session.djangoToken;
// return fetch(`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/pieces/`, {
// http://localhost:8000/api/courses/6th-grade-band/piece-plans/
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${courseSlug}/piece-plans/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
}
)
.then(assertResponse)
.then((response) => response.json())
.then((json) => {
const result = json;
return result.map((r) => ({...r.piece, piece_plan_id: r.id}));
});
});
}
export function getAssignedPieces(assignments) {
return () => {
const pieces = {};
if (Object.values(assignments).length > 0) {
for (const pieceKey of Object.keys(assignments)) {
for (const pieceAssignment of assignments[pieceKey]) {
// pieces[pieceAssignment.part.piece.id] = pieceAssignment.part.piece;
// }
if (!(pieceKey in pieces)) {
pieces[pieceKey] = {
id: pieceAssignment.piece_id,
name: pieceAssignment.piece_name,
activities: {},
slug: pieceAssignment.piece_slug,
};
}
const actType = pieceAssignment.activity_type_name;
const actCat = pieceAssignment.activity_type_category;
pieces[pieceKey].activities[`${actCat}-${actType}`] = {
name: actType,
category: actCat,
};
}
}
}
return pieces;
};
export function getAllPieces(slug) {
return async () => {
const endpoint = `courses/${slug}/piece-plans/`;
const json = await makeRequest(endpoint);
return json.map((r) => ({...r.piece, piece_plan_id: r.id}));
}
}

export function mutateAssignPiece(slug) {
return (piecePlanId) =>
getSession().then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/assign_piece_plan/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({ piece_plan_id: piecePlanId }),
// body: data,
}
)
.then(assertResponse)
.then((response) => response.json());
});
return async (piecePlanId) => {
const endpoint = `courses/${slug}/assign_piece_plan/`
const json = await makeRequest(endpoint, method='POST', body={piece_id: piecePlanId})
return json
}
}

export function mutateUnassignPiece(slug) {
return (piece) =>
getSession().then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/unassign/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({ piece_id: piece.id }),
// body: data,
}
);
});
return async (piece) => {
const endpoint = `courses/${slug}/unassign/`
const json = await makeRequest(endpoint, method='POST', body={piece_id: piece.id});
return json
}
}

export function getRecentSubmissions({ slug, piece, partType }) {
return () =>
getSession().then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/submissions/recent/?piece_slug=${piece}&activity_name=${partType}`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
}
)
.then(assertResponse)
.then((response) => response.json())
});
return async () => {
const endpoint = `courses/${slug}/submissions/recent/?piece_slug=${piece}&activity_name=${partType}`;
const json = await makeRequest(endpoint);
return json;
}
}

export function mutateGradeSubmission(slug) {
return ({ student_submission, rhythm, tone, expression, grader }) =>
getSession().then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/grades/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
student_submission: [student_submission],
own_submission: [],
rhythm,
tone,
expression,
grader,
}),
// body: data,
}
)
.then(assertResponse)
.then((response) => response.json());
});
return async ({ student_submission, rhythm, tone, expression, grader }) => {
const endpoint = `courses/${slug}/grades/`;
const body = {
student_submission: [student_submission],
own_submission: [],
rhythm,
tone,
expression,
grader
};
const json = await makeRequest(endpoint, method='POST', body=body);
return json;
}
}

// should i make this mutator optionally have a recording or??
export function mutateCreateSubmission({ slug }) {
return (submission, assignmentId) =>
getSession()
.then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/assignments/${assignmentId}/submissions/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(submission),
}
);
})
.then(assertResponse)
.then((res) => res.json());
return async (submission, assignmentId) => {
const endpoint = `courses/${slug}/assignments/${assignmentId}/submissions/`
const json = await makeRequest(endpoint, method='POST', body=submission)
return json;
}
}

export function getMySubmissionsForAssignment({ slug, assignmentId }) {
return getSession()
.then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/assignments/${assignmentId}/submissions/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
}
);
})
.then(assertResponse)
.then((response) => response.json())
export async function getMySubmissionsForAssignment({ slug, assignmentId }) {
const endpoint = `courses/${slug}/assignments/${assignmentId}/submissions/`
const json = await makeRequest(endpoint);
return json;
}

export function mutateCourse(slug) {
// expecting params to be any subset of name, start_date, end_date, slug
return (params) => {
return getSession().then((session) => {
const token = session.djangoToken;
return fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'PATCH',
body: JSON.stringify(params),
// body: data,
}
)
.then(assertResponse)
.then((response) => response.json());
});
};
return async (params) => {
const endpoint = `courses/${slug}/`
const json = await makeRequest(endpoint, method='PATCH', body=params);
return json;
}
}



export async function mutateAssignmentInstrument(slug, pieceId, instrument) {
const session = await getSession();
const token = session.djangoToken;
const response = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_HOST}/api/courses/${slug}/change_piece_instrument/`,
{
headers: {
Authorization: `Token ${token}`,
'Content-Type': 'application/json',
},
method: 'PATCH',
body: JSON.stringify({piece_id: pieceId ,instrument_id: instrument.id})
const endpoint = `courses/${slug}/change_piece_instrument/`;
const body = {piece_id: pieceId, instrument_id: instrument.id};
const json = await makeRequest(endpoint, method='PATCH', body=body);
return json;
}

export function getAssignedPieces(assignments) {
return () => {
const pieces = {};
if (Object.values(assignments).length == 0) return pieces;

for (const pieceKey of Object.keys(assignments)) {
for (const pieceAssignment of assignments[pieceKey]) {
if (!(pieceKey in pieces)) {
pieces[pieceKey] = {
id: pieceAssignment.piece_id,
name: pieceAssignment.piece_name,
activities: {},
slug: pieceAssignment.piece_slug,
};
}
const actType = pieceAssignment.activity_type_name;
const actCat = pieceAssignment.activity_type_category;
pieces[pieceKey].activities[`${actCat}-${actType}`] = {
name: actType,
category: actCat,
};
}
}
);

assertResponse(response);
return pieces;
};
}

0 comments on commit 82ef29b

Please sign in to comment.