feat: enhance API route naming conventions and structure

- Added comprehensive guidelines for API route naming and structure in `ROUTE_NAMING_BEST_PRACTICES.md`.
- Updated `ARCHITECHTURE.md` to reference the new best practices document.
- Refactored course-related routes to follow new naming conventions, including changes to endpoint paths and validation schemas.
- Removed the deprecated course clone route and integrated cloning functionality directly into the course routes.
- Adjusted various API methods to ensure consistent usage of HTTP methods and parameter structures across the application.
This commit is contained in:
Rotimi Best
2025-12-05 17:24:16 +01:00
parent eff364baa4
commit 4b52906445
34 changed files with 777 additions and 189 deletions
@@ -88,8 +88,8 @@ export class ProfileApi extends BaseApiWithErrors {
return;
}
await this.execute<typeof classroomio.account.user.$put>({
requestFn: () => classroomio.account.user.$put({ json: profileUpdates }),
await this.execute<typeof classroomio.account.profile.$put>({
requestFn: () => classroomio.account.profile.$put({ json: profileUpdates }),
logContext: 'updating profile',
onSuccess: (response) => {
profileStore.update((_profile) => ({
@@ -0,0 +1,80 @@
import { BaseApiWithErrors, classroomio } from '$lib/utils/services/api';
import { copyCourseModal, copyCourseModalInitialState } from '../utils/store';
import type { TCourseClone } from '@cio/utils/validation/course';
import { ZCourseClone } from '@cio/utils/validation/course';
import { currentOrg } from '$lib/utils/store/org';
import generateSlug from '$lib/utils/functions/generateSlug';
import { get } from 'svelte/store';
import { goto } from '$app/navigation';
import { mapZodErrorsToTranslations } from '$lib/utils/validation';
import { resolve } from '$app/paths';
import { snackbar } from '$lib/components/Snackbar/store';
import { t } from '$lib/utils/functions/translations';
/**
* API class for course operations
*/
export class CourseCloneApi extends BaseApiWithErrors {
/**
* Clones a course
* @param courseId The ID of the course to clone
* @param title Course title
* @param description Course description (optional)
* @returns The cloned course data or null on error
*/
async clone(courseId: string, title: string, description?: string) {
// Generate unique slug from the title
const slug = generateSlug(title);
// Prepare data for validation
const data: TCourseClone = {
title,
description,
slug,
organizationId: get(currentOrg).id
};
// Client-side validation
const result = ZCourseClone.safeParse(data);
if (!result.success) {
this.errors = mapZodErrorsToTranslations(result.error, 'course');
return null;
}
await this.execute<(typeof classroomio.course)[':courseId']['clone']['$post']>({
requestFn: () =>
classroomio.course[':courseId'].clone.$post({
param: { courseId },
// @ts-expect-error - the json type is not inferred correctly
json: result.data
}),
logContext: 'cloning course',
onSuccess: (response) => {
this.errors = {};
copyCourseModal.set(copyCourseModalInitialState);
copyCourseModal.update((modal) => ({ ...modal, open: false }));
// Navigate to the new course
goto(resolve(`/courses/${response.course.id}`, {}));
snackbar.success(t.get('courses.copy_course.success.course_cloned'));
},
onError: (result) => {
if (typeof result === 'string') {
snackbar.error(result);
return;
}
if ('error' in result && 'field' in result) {
// Field-specific error automatically mapped to this.errors[field]
this.errors[result.field as string] = result.error;
} else if ('error' in result) {
snackbar.error(result.error);
}
}
});
}
}
export const courseCloneApi = new CourseCloneApi();
@@ -0,0 +1 @@
export * from './course-clone.svelte';
@@ -1,64 +1,23 @@
<script lang="ts">
import { preventDefault } from '$lib/utils/functions/svelte';
import { goto } from '$app/navigation';
import PrimaryButton from '$lib/components/PrimaryButton/index.svelte';
import Modal from '$lib/components/Modal/index.svelte';
import { snackbar } from '$lib/components/Snackbar/store';
import TextField from '$lib/components/Form/TextField.svelte';
import TextArea from '$lib/components/Form/TextArea.svelte';
import { copyCourseModalInitialState, copyCourseModal } from '$lib/features/course/utils/store';
import { classroomio } from '$lib/utils/services/api';
import generateSlug from '$lib/utils/functions/generateSlug';
import { currentOrg } from '$lib/utils/store/org';
import { copyCourseModal } from '$lib/features/course/utils/store';
import { courseCloneApi } from '$lib/features/course/api';
import { t } from '$lib/utils/functions/translations';
// clone, show spinner and redirect to new course
async function createCourse() {
// Prevent double submission (Option 1: Early Return Guard)
if ($copyCourseModal.isSaving) return;
if ($copyCourseModal.isSaving || courseCloneApi.isLoading) return;
console.log('Create course');
$copyCourseModal.isSaving = true;
try {
// Generate unique slug from the title
const slug = generateSlug($copyCourseModal.title);
const response = await classroomio.course.clone.$post({
json: {
id: $copyCourseModal.id,
title: $copyCourseModal.title,
description: $copyCourseModal.description,
slug,
organizationId: $currentOrg.id
}
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.error || $t('courses.copy_course.error.failed_to_clone'));
}
// Option 3: Close modal and reset state before navigation
copyCourseModal.set(copyCourseModalInitialState);
// Navigate to the new course
goto(`/courses/${result.course.id}`);
$copyCourseModal.open = false;
} catch (error) {
console.error(error);
// IIFI of snackbar to Show notification error
(() => {
snackbar.error();
})();
// Stop loader
$copyCourseModal.isSaving = false;
}
await courseCloneApi.clone($copyCourseModal.id, $copyCourseModal.title, $copyCourseModal.description);
}
// Sync loading state with modal store
$effect(() => {
$copyCourseModal.isSaving = courseCloneApi.isLoading;
});
</script>
<Modal
@@ -76,6 +35,7 @@
className="mb-4"
isRequired={true}
autoComplete={false}
errorMessage={courseCloneApi.errors.title}
/>
<TextArea
@@ -84,8 +44,13 @@
placeholder={$t('courses.copy_course.course_description_placeholder')}
className="mb-4"
rows={4}
errorMessage={courseCloneApi.errors.description}
/>
{#if courseCloneApi.errors.general}
<div class="mb-4 text-sm text-red-600">{courseCloneApi.errors.general}</div>
{/if}
<div class="mt-5 flex flex-row-reverse items-center">
<PrimaryButton
className="px-6 py-3"
@@ -32,8 +32,8 @@ export class OnboardingApi extends BaseApiWithErrors {
return false;
}
await this.execute<typeof classroomio.onboarding.step1.$post>({
requestFn: () => classroomio.onboarding.step1.$post({ json: data }),
await this.execute<(typeof classroomio.onboarding)['create-org']['$post']>({
requestFn: () => classroomio.onboarding['create-org'].$post({ json: data }),
logContext: 'submitting organization setup',
onSuccess: (result) => {
const { organizations } = result.data;
@@ -70,8 +70,8 @@ export class OnboardingApi extends BaseApiWithErrors {
return false;
}
await this.execute<typeof classroomio.onboarding.step2.$post>({
requestFn: () => classroomio.onboarding.step2.$post({ json: data }),
await this.execute<(typeof classroomio.onboarding)['update-metadata']['$post']>({
requestFn: () => classroomio.onboarding['update-metadata'].$post({ json: data }),
logContext: 'submitting organization setup',
onSuccess: (result) => {
profile.set(result.data);
@@ -1,5 +1,5 @@
import type { OnboardingField, OnboardingStep } from './types';
import { ZOnboardingStep1, ZOnboardingStep2 } from '@cio/utils/validation/onboarding';
import { ZOnboardingCreateOrg, ZOnboardingUpdateMetadata } from '@cio/utils/validation/onboarding';
import { ONBOARDING_STEPS } from './constants';
import { blockedSubdomain } from '@cio/utils/constants';
@@ -11,14 +11,14 @@ export const onboardingValidation = (field: OnboardingField, step: OnboardingSte
return { siteName: 'Sitename already exists.' };
}
const result = ZOnboardingStep1.safeParse(field);
const result = ZOnboardingCreateOrg.safeParse(field);
if (!result.success) {
return mapZodErrorsToTranslations(result.error);
}
}
if (step === ONBOARDING_STEPS.USER_METADATA) {
const result = ZOnboardingStep2.safeParse(field);
const result = ZOnboardingUpdateMetadata.safeParse(field);
if (!result.success) {
return mapZodErrorsToTranslations(result.error);
}
@@ -21,8 +21,8 @@ class DashStatApi extends BaseApi {
* @returns Organization analytics data (enrollments, courses, revenue, students, top courses)
*/
async fetchOrgStats({ orgId, siteName }: { orgId?: string; siteName?: string }) {
await this.execute<typeof classroomio.dash.stats.$post>({
requestFn: () => classroomio.dash.stats.$post({ json: { orgId, siteName } }),
await this.execute<typeof classroomio.dash.stats.$get>({
requestFn: () => classroomio.dash.stats.$get({ query: { orgId, siteName } }),
logContext: 'fetching organization stats',
onSuccess: (response) => {
this.stats = response.data;
@@ -276,7 +276,7 @@ class OrgApi extends BaseApiWithErrors {
async inviteTeamMembers(orgId: string, emails: string[], roleId: number) {
return this.execute<InviteTeamResponse>({
requestFn: () =>
classroomio.organization[':orgId'].team.invite.$post({
classroomio.organization[':orgId']['team']['invite']['$post']({
param: { orgId },
// @ts-expect-error - the json type is not inferred correctly
json: { emails, roleId }
@@ -34,7 +34,7 @@ export type CoursesByOrganizationSiteNameSuccess = Extract<
export type CoursesByOrganizationSiteName = CoursesByOrganizationSiteNameSuccess['data'];
// dashboard analytics types
export type GetDashStatsResponse = typeof classroomio.dash.stats.$post;
export type GetDashStatsResponse = typeof classroomio.dash.stats.$get;
export type DashStatsResponse = InferResponseType<GetDashStatsResponse> | null;
export type DashStatsSuccess = Extract<InferResponseType<GetDashStatsResponse>, { success: true }>;