Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: proper types for seeds #212

Merged
merged 8 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions .github/workflows/deploy-api-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,11 @@ jobs:
ECS_CLUSTER: ${{ secrets.AWS_ECS_CLUSTER }}
ECS_SERVICE: ${{ secrets.AWS_ECS_SERVICE }}
DOCKER_IMAGE: ${{ secrets.AWS_ECR_REGISTRY }}:${{ github.sha }}
run: selleo aws ecs deploy --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --docker-image $DOCKER_IMAGE --one-off migrate --one-off seed
run: selleo aws ecs deploy --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --docker-image $DOCKER_IMAGE --one-off migrate

- name: ECS Run migrations
env:
AWS_REGION: ${{ secrets.AWS_REGION }}
ECS_CLUSTER: ${{ secrets.AWS_ECS_CLUSTER }}
ECS_SERVICE: ${{ secrets.AWS_ECS_SERVICE }}
run: selleo aws ecs run --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --one-off migrate

- name: ECS Run seeds
env:
AWS_REGION: ${{ secrets.AWS_REGION }}
ECS_CLUSTER: ${{ secrets.AWS_ECS_CLUSTER }}
ECS_SERVICE: ${{ secrets.AWS_ECS_SERVICE }}
run: selleo aws ecs run --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --one-off seed
4 changes: 2 additions & 2 deletions .github/workflows/deploy-api-staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ jobs:
ECS_CLUSTER: ${{ vars.AWS_ECS_CLUSTER }}
ECS_SERVICE: ${{ vars.AWS_ECS_SERVICE }}
DOCKER_IMAGE: ${{ secrets.AWS_ECR_REGISTRY }}:${{ github.sha }}
run: selleo aws ecs deploy --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --docker-image $DOCKER_IMAGE --one-off migrate --one-off seed
run: selleo aws ecs deploy --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --docker-image $DOCKER_IMAGE --one-off migrate

- name: ECS Run migrations
env:
Expand All @@ -70,4 +70,4 @@ jobs:
AWS_REGION: ${{ vars.AWS_REGION }}
ECS_CLUSTER: ${{ vars.AWS_ECS_CLUSTER }}
ECS_SERVICE: ${{ vars.AWS_ECS_SERVICE }}
run: selleo aws ecs run --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --one-off seed
run: selleo aws ecs run --region $AWS_REGION --cluster $ECS_CLUSTER --service $ECS_SERVICE --one-off storage/seed/seed
2 changes: 1 addition & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"test:e2e:watch": "jest --config ./test/jest-e2e.json --watch",
"db:migrate": "drizzle-kit migrate",
"db:generate": "drizzle-kit generate",
"db:seed": "ts-node -r tsconfig-paths/register ./src/seed.ts",
"db:seed": "ts-node -r tsconfig-paths/register ./src/storage/seed/seed.ts",
"db:seed-prod": "node dist/src/seed.js"
},
"dependencies": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import request from "supertest";

import { UserRoles } from "src/users/schemas/user-roles";
import { USER_ROLES } from "src/users/schemas/user-roles";

import { createE2ETest } from "../../../test/create-e2e-test";
import { createCategoryFactory } from "../../../test/factory/category.factory";
Expand Down Expand Up @@ -38,7 +38,7 @@ describe("CategoriesController (e2e)", () => {
it("returns archived and createdAt equal to null", async () => {
const user = await userFactory
.withCredentials({ password })
.create({ role: UserRoles.student });
.create({ role: USER_ROLES.student });

const response = await request(app.getHttpServer())
.get("/api/categories")
Expand All @@ -58,7 +58,7 @@ describe("CategoriesController (e2e)", () => {
it("returns all filled category columns", async () => {
const user = await userFactory
.withCredentials({ password })
.create({ role: UserRoles.admin });
.create({ role: USER_ROLES.admin });

const response = await request(app.getHttpServer())
.get("/api/categories")
Expand All @@ -81,7 +81,7 @@ describe("CategoriesController (e2e)", () => {
let page = 1;
const user = await userFactory
.withCredentials({ password })
.create({ role: UserRoles.student });
.create({ role: USER_ROLES.student });

const response = await request(app.getHttpServer())
.get(`/api/categories?perPage=${perPage}&page=${page}`)
Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/categories/__tests__/categories.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DEFAULT_PAGE_SIZE } from "src/common/pagination";
import { categories } from "src/storage/schema";
import { type UserRole, UserRoles } from "src/users/schemas/user-roles";
import { USER_ROLES } from "src/users/schemas/user-roles";
import { createUnitTest, type TestContext } from "test/create-unit-test";
import { createCategoryFactory } from "test/factory/category.factory";
import { truncateAllTables } from "test/helpers/test-helpers";
Expand All @@ -9,6 +9,7 @@ import { CategoriesService } from "../categories.service";

import type { CategoriesQuery } from "../api/categories.types";
import type { DatabasePg } from "src/common";
import type { UserRole } from "src/users/schemas/user-roles";

const CATEGORIES_COUNT = 20;

Expand Down Expand Up @@ -36,7 +37,7 @@ describe("CategoriesService", () => {
describe("getCategories", () => {
describe("when the request specifies the pagination params", () => {
it("returns correct pagination data", async () => {
userRole = UserRoles.student;
userRole = USER_ROLES.student;
const perPage = 5;
const page = 2,
query = { page, perPage };
Expand Down
18 changes: 9 additions & 9 deletions apps/api/src/categories/api/categories.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
type UUIDType,
} from "src/common";
import { CurrentUser } from "src/common/decorators/user.decorator";
import { UserRole } from "src/users/schemas/user-roles";
import { USER_ROLES, UserRole } from "src/users/schemas/user-roles";

import { CategoriesService } from "../categories.service";
import {
Expand All @@ -23,8 +23,8 @@ import {
type SortCategoryFieldsOptions,
sortCategoryFieldsOptions,
} from "../schemas/categoryQuery";
import { type CreateCategoryBody, createCategorySchema } from "../schemas/createCategorySchema";
import { type UpdateCategoryBody, updateCategorySchema } from "../schemas/updateCategorySchema";
import { categoryCreateSchema, type CategoryInsert } from "../schemas/createCategorySchema";
import { categoryUpdateSchema, type CategoryUpdateBody } from "../schemas/updateCategorySchema";

@Controller("categories")
export class CategoriesController {
Expand Down Expand Up @@ -66,7 +66,7 @@ export class CategoriesController {
@Query("id") id: string,
@CurrentUser() currentUser: { role: string },
): Promise<BaseResponse<CategorySchema>> {
if (currentUser.role !== "admin") {
if (currentUser.role !== USER_ROLES.admin) {
throw new UnauthorizedException("You don't have permission to get category");
}

Expand All @@ -80,13 +80,13 @@ export class CategoriesController {
request: [
{
type: "body",
schema: createCategorySchema,
schema: categoryCreateSchema,
},
],
response: baseResponse(Type.Object({ id: UUIDSchema, message: Type.String() })),
})
async createCategory(
@Body() createCategoryBody: CreateCategoryBody,
@Body() createCategoryBody: CategoryInsert,
): Promise<BaseResponse<{ id: UUIDType; message: string }>> {
const { id } = await this.categoriesService.createCategory(createCategoryBody);

Expand All @@ -98,15 +98,15 @@ export class CategoriesController {
response: baseResponse(categorySchema),
request: [
{ type: "param", name: "id", schema: Type.String() },
{ type: "body", schema: updateCategorySchema },
{ type: "body", schema: categoryUpdateSchema },
],
})
async updateCategory(
@Query("id") id: string,
@Body() updateCategoryBody: UpdateCategoryBody,
@Body() updateCategoryBody: CategoryUpdateBody,
@CurrentUser() currentUser: { role: string },
): Promise<BaseResponse<CategorySchema>> {
if (currentUser.role !== "admin") {
if (currentUser.role !== USER_ROLES.admin) {
throw new UnauthorizedException("You don't have permission to update category");
}

Expand Down
15 changes: 8 additions & 7 deletions apps/api/src/categories/categories.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import {
} from "@nestjs/common";
import { and, count, eq, ilike, like } from "drizzle-orm";

import { DatabasePg, type Pagination } from "src/common";
import { DatabasePg } from "src/common";
import { getSortOptions } from "src/common/helpers/getSortOptions";
import { addPagination, DEFAULT_PAGE_SIZE } from "src/common/pagination";
import { categories } from "src/storage/schema";
import { UserRoles, type UserRole } from "src/users/schemas/user-roles";
import { type UserRole, USER_ROLES } from "src/users/schemas/user-roles";

import {
type CategoryFilterSchema,
Expand All @@ -20,8 +20,9 @@ import {

import type { CategoriesQuery } from "./api/categories.types";
import type { AllCategoriesResponse } from "./schemas/category.schema";
import type { CreateCategoryBody } from "./schemas/createCategorySchema";
import type { UpdateCategoryBody } from "./schemas/updateCategorySchema";
import type { CategoryInsert } from "./schemas/createCategorySchema";
import type { CategoryUpdateBody } from "./schemas/updateCategorySchema";
import type { Pagination } from "src/common";

@Injectable()
export class CategoriesService {
Expand All @@ -40,7 +41,7 @@ export class CategoriesService {

const { sortOrder, sortedField } = getSortOptions(sort);

const isAdmin = userRole === UserRoles.admin;
const isAdmin = userRole === USER_ROLES.admin;

const selectedColumns = {
id: categories.id,
Expand Down Expand Up @@ -81,15 +82,15 @@ export class CategoriesService {
return category;
}

public async createCategory(createCategoryBody: CreateCategoryBody) {
public async createCategory(createCategoryBody: CategoryInsert) {
const [newCategory] = await this.db.insert(categories).values(createCategoryBody).returning();

if (!newCategory) throw new UnprocessableEntityException("Category not created");

return newCategory;
}

public async updateCategory(id: string, updateCategoryBody: UpdateCategoryBody) {
public async updateCategory(id: string, updateCategoryBody: CategoryUpdateBody) {
const [existingCategory] = await this.db.select().from(categories).where(eq(categories.id, id));

if (!existingCategory) {
Expand Down
9 changes: 0 additions & 9 deletions apps/api/src/categories/schemas/categoryCommon.schema.ts

This file was deleted.

10 changes: 6 additions & 4 deletions apps/api/src/categories/schemas/createCategorySchema.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { type Static, Type } from "@sinclair/typebox";
import { Type } from "@sinclair/typebox";

export const createCategorySchema = Type.Object({
import type { InferInsertModel } from "drizzle-orm";
import type { categories } from "src/storage/schema";

export const categoryCreateSchema = Type.Object({
title: Type.String(),
});

export type CreateCategoryBody = Static<typeof createCategorySchema>;
export type CategoryInsert = InferInsertModel<typeof categories>;
8 changes: 5 additions & 3 deletions apps/api/src/categories/schemas/updateCategorySchema.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { type Static, Type } from "@sinclair/typebox";
import { Type } from "@sinclair/typebox";

import { UUIDSchema } from "src/common";

export const updateCategorySchema = Type.Partial(
import type { CategoryInsert } from "./createCategorySchema";

export const categoryUpdateSchema = Type.Partial(
Type.Object({
id: UUIDSchema,
title: Type.String(),
archived: Type.Boolean(),
}),
);

export type UpdateCategoryBody = Static<typeof updateCategorySchema>;
export type CategoryUpdateBody = Partial<Pick<CategoryInsert, "title" | "archived">>;
4 changes: 4 additions & 0 deletions apps/api/src/common/states.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const STATES = {
draft: "draft",
published: "published",
} as const;
5 changes: 3 additions & 2 deletions apps/api/src/courses/api/courses.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import { Roles } from "src/common/decorators/roles.decorator";
import { CurrentUser } from "src/common/decorators/user.decorator";
import { RolesGuard } from "src/common/guards/roles.guard";
import { USER_ROLES } from "src/users/schemas/user-roles";

import { CoursesService } from "../courses.service";
import { SortCourseFieldsOptions } from "../schemas/courseQuery";
Expand Down Expand Up @@ -158,7 +159,7 @@ export class CoursesController {
}

@Get("course-by-id")
@Roles("tutor", "admin")
@Roles(USER_ROLES.tutor, USER_ROLES.admin)
@Validate({
request: [{ type: "query", name: "id", schema: UUIDSchema, required: true }],
response: baseResponse(commonShowCourseSchema),
Expand All @@ -183,7 +184,7 @@ export class CoursesController {

@Patch(":id")
@UseInterceptors(FileInterceptor("image"))
@Roles("tutor", "admin")
@Roles(USER_ROLES.tutor, USER_ROLES.admin)
@Validate({
request: [
{ type: "param", name: "id", schema: UUIDSchema },
Expand Down
24 changes: 21 additions & 3 deletions apps/api/src/courses/courses.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ export class CoursesService {
SELECT COUNT(*)
FROM ${studentCompletedLessonItems}
WHERE ${studentCompletedLessonItems.lessonId} = ${lessons.id}
AND ${studentCompletedLessonItems.courseId} = ${courses.id}
AND ${studentCompletedLessonItems.studentId} = ${userId}
)
)::INTEGER`,
Expand All @@ -302,18 +303,28 @@ export class CoursesService {
id: lessons.id,
title: lessons.title,
type: lessons.type,
isSubmitted: sql<boolean>`EXISTS (SELECT 1 FROM ${studentLessonsProgress} WHERE ${studentLessonsProgress.lessonId} = ${lessons.id} AND ${studentLessonsProgress.studentId} = ${userId} AND ${studentLessonsProgress.quizCompleted})::BOOLEAN`,
isSubmitted: sql<boolean>`
EXISTS (
SELECT 1
FROM ${studentLessonsProgress}
WHERE ${studentLessonsProgress.lessonId} = ${lessons.id}
AND ${studentLessonsProgress.courseId} = ${course.id}
AND ${studentLessonsProgress.studentId} = ${userId}
AND ${studentLessonsProgress.quizCompleted}
)::BOOLEAN`,
description: sql<string>`${lessons.description}`,
imageUrl: sql<string>`${lessons.imageUrl}`,
itemsCount: sql<number>`
(SELECT COUNT(*)
FROM ${lessonItems}
WHERE ${lessonItems.lessonId} = ${lessons.id} AND ${lessonItems.lessonItemType} != 'text_block')::INTEGER`,
WHERE ${lessonItems.lessonId} = ${lessons.id}
AND ${lessonItems.lessonItemType} != 'text_block')::INTEGER`,
itemsCompletedCount: sql<number>`
(SELECT COUNT(*)
FROM ${studentCompletedLessonItems}
WHERE ${studentCompletedLessonItems.lessonId} = ${lessons.id}
AND ${studentCompletedLessonItems.studentId} = ${userId})::INTEGER`,
AND ${studentCompletedLessonItems.courseId} = ${course.id}
AND ${studentCompletedLessonItems.studentId} = ${userId})::INTEGER`,
lessonProgress: sql<"completed" | "in_progress" | "not_started">`
(CASE
WHEN (
Expand All @@ -325,13 +336,15 @@ export class CoursesService {
SELECT COUNT(*)
FROM ${studentCompletedLessonItems}
WHERE ${studentCompletedLessonItems.lessonId} = ${lessons.id}
AND ${studentCompletedLessonItems.courseId} = ${course.id}
AND ${studentCompletedLessonItems.studentId} = ${userId}
)
THEN ${LessonProgress.completed}
WHEN (
SELECT COUNT(*)
FROM ${studentCompletedLessonItems}
WHERE ${studentCompletedLessonItems.lessonId} = ${lessons.id}
AND ${studentCompletedLessonItems.courseId} = ${course.id}
AND ${studentCompletedLessonItems.studentId} = ${userId}
) > 0
THEN ${LessonProgress.inProgress}
Expand Down Expand Up @@ -585,6 +598,7 @@ export class CoursesService {
quizLessons.map((lesson) => ({
studentId: userId,
lessonId: lesson.id,
courseId: course.id,
quizCompleted: false,
lessonItemCount: lesson.itemCount,
completedLessonItemCount: 0,
Expand Down Expand Up @@ -630,6 +644,7 @@ export class CoursesService {
.delete(studentLessonsProgress)
.where(
and(
eq(studentLessonsProgress.courseId, id),
inArray(studentLessonsProgress.lessonId, courseLessonsIds),
eq(studentLessonsProgress.studentId, userId),
),
Expand All @@ -640,6 +655,7 @@ export class CoursesService {
.delete(studentQuestionAnswers)
.where(
and(
eq(studentQuestionAnswers.courseId, course.id),
inArray(studentQuestionAnswers.lessonId, courseLessonsIds),
eq(studentQuestionAnswers.studentId, userId),
),
Expand All @@ -650,6 +666,7 @@ export class CoursesService {
.delete(studentCompletedLessonItems)
.where(
and(
eq(studentCompletedLessonItems.courseId, id),
inArray(studentCompletedLessonItems.lessonId, courseLessonsIds),
eq(studentCompletedLessonItems.studentId, userId),
),
Expand Down Expand Up @@ -710,6 +727,7 @@ export class CoursesService {
SELECT COUNT(*)
FROM ${studentCompletedLessonItems}
WHERE ${studentCompletedLessonItems.lessonId} = ${lessons.id}
AND ${studentCompletedLessonItems.courseId} = ${courses.id}
AND ${studentCompletedLessonItems.studentId} = ${userId}
)
)::INTEGER`,
Expand Down
Loading