Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat: teamCollection module added

Mir Arif Hasan4b424962734a
diff --git a/packages/hoppscotch-backend/src/app.module.ts b/packages/hoppscotch-backend/src/app.module.ts
index 32bfed4ac..bd81838ea 100644
--- a/packages/hoppscotch-backend/src/app.module.ts
+++ b/packages/hoppscotch-backend/src/app.module.ts
@@ -10,6 +10,7 @@ import { UserHistoryModule } from './user-history/user-history.module';
import { subscriptionContextCookieParser } from './auth/helper';
import { TeamModule } from './team/team.module';
import { TeamEnvironmentsModule } from './team-environments/team-environments.module';
+import { TeamCollectionModule } from './team-collection/team-collection.module';
@Module({
imports: [
@@ -49,6 +50,7 @@ import { TeamEnvironmentsModule } from './team-environments/team-environments.mo
UserHistoryModule,
TeamModule,
TeamEnvironmentsModule,
+ TeamCollectionModule,
],
providers: [GQLComplexityPlugin],
})
diff --git a/packages/hoppscotch-backend/src/pubsub/topicsDefs.ts b/packages/hoppscotch-backend/src/pubsub/topicsDefs.ts
index 199772ec3..cd7580168 100644
--- a/packages/hoppscotch-backend/src/pubsub/topicsDefs.ts
+++ b/packages/hoppscotch-backend/src/pubsub/topicsDefs.ts
@@ -4,6 +4,7 @@ import { UserEnvironment } from '../user-environment/user-environments.model';
import { UserHistory } from '../user-history/user-history.model';
import { TeamMember } from 'src/team/team.model';
import { TeamEnvironment } from 'src/team-environments/team-environments.model';
+import { TeamCollection } from 'src/team-collection/team-collection.model';
// A custom message type that defines the topic and the corresponding payload.
// For every module that publishes a subscription add its type def and the possible subscription type.
@@ -18,10 +19,15 @@ export type TopicDef = {
topic: `user_history/${string}/${'created' | 'updated' | 'deleted'}`
]: UserHistory;
[topic: `team/${string}/member_removed`]: string;
- [topic: `team/${string}/member_added`]: TeamMember;
- [topic: `team/${string}/member_updated`]: TeamMember;
- [topic: `team_environment/${string}/created`]: TeamEnvironment;
- [topic: `team_environment/${string}/updated`]: TeamEnvironment;
- [topic: `team_environment/${string}/deleted`]: TeamEnvironment;
+ [topic: `team/${string}/${'member_added' | 'member_updated'}`]: TeamMember;
+ [
+ topic: `team_environment/${string}/${'created' | 'updated' | 'deleted'}`
+ ]: TeamEnvironment;
+ [
+ topic: `team_coll/${string}/${
+ | 'coll_added'
+ | 'coll_updated'
+ | 'coll_removed'}`
+ ]: TeamCollection;
[topic: `user_history/${string}/deleted_many`]: number;
};
diff --git a/packages/hoppscotch-backend/src/team-collection/guards/gql-collection-team-member.guard.ts b/packages/hoppscotch-backend/src/team-collection/guards/gql-collection-team-member.guard.ts
new file mode 100644
index 000000000..1d8dded6d
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/guards/gql-collection-team-member.guard.ts
@@ -0,0 +1,51 @@
+import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
+import { Reflector } from '@nestjs/core';
+import { GqlExecutionContext } from '@nestjs/graphql';
+import { User } from '../../user/user.model';
+import { TeamCollectionService } from '../team-collection.service';
+import { TeamService } from '../../team/team.service';
+import { TeamMemberRole } from '../../team/team.model';
+import {
+ BUG_TEAM_NO_REQUIRE_TEAM_ROLE,
+ BUG_AUTH_NO_USER_CTX,
+ BUG_TEAM_COLL_NO_COLL_ID,
+ TEAM_INVALID_COLL_ID,
+ TEAM_REQ_NOT_MEMBER,
+} from 'src/errors';
+
+@Injectable()
+export class GqlCollectionTeamMemberGuard implements CanActivate {
+ constructor(
+ private readonly reflector: Reflector,
+ private readonly teamService: TeamService,
+ private readonly teamCollectionService: TeamCollectionService,
+ ) {}
+
+ async canActivate(context: ExecutionContext): Promise<boolean> {
+ const requireRoles = this.reflector.get<TeamMemberRole[]>(
+ 'requiresTeamRole',
+ context.getHandler(),
+ );
+ if (!requireRoles) throw new Error(BUG_TEAM_NO_REQUIRE_TEAM_ROLE);
+
+ const gqlExecCtx = GqlExecutionContext.create(context);
+ const { user } = gqlExecCtx.getContext().req;
+ if (user == undefined) throw new Error(BUG_AUTH_NO_USER_CTX);
+
+ const { collectionID } = gqlExecCtx.getArgs<{ collectionID: string }>();
+ if (!collectionID) throw new Error(BUG_TEAM_COLL_NO_COLL_ID);
+
+ const collection = await this.teamCollectionService.getCollection(
+ collectionID,
+ );
+ if (!collection) throw new Error(TEAM_INVALID_COLL_ID);
+
+ const member = await this.teamService.getTeamMember(
+ collection.teamID,
+ user.uid,
+ );
+ if (!member) throw new Error(TEAM_REQ_NOT_MEMBER);
+
+ return requireRoles.includes(member.role);
+ }
+}
diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts
new file mode 100644
index 000000000..32b1b07cb
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts
@@ -0,0 +1,17 @@
+import { ObjectType, Field, ID } from '@nestjs/graphql';
+
+@ObjectType()
+export class TeamCollection {
+ @Field(() => ID, {
+ description: 'ID of the collection',
+ })
+ id: string;
+
+ @Field({
+ description: 'Displayed title of the collection',
+ })
+ title: string;
+
+ parentID: string | null;
+ teamID: string;
+}
diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.module.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.module.ts
new file mode 100644
index 000000000..dda0236da
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.module.ts
@@ -0,0 +1,26 @@
+import { Module } from '@nestjs/common';
+import { PrismaModule } from '../prisma/prisma.module';
+import { TeamCollectionService } from './team-collection.service';
+import { TeamCollectionResolver } from './team-collection.resolver';
+import { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';
+import { TeamModule } from '../team/team.module';
+import { UserModule } from '../user/user.module';
+// import { FirebaseModule } from '../firebase/firebase.module';
+import { PubSubModule } from '../pubsub/pubsub.module';
+
+@Module({
+ imports: [
+ PrismaModule,
+ // FirebaseModule,
+ TeamModule,
+ UserModule,
+ PubSubModule,
+ ],
+ providers: [
+ TeamCollectionService,
+ TeamCollectionResolver,
+ GqlCollectionTeamMemberGuard,
+ ],
+ exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],
+})
+export class TeamCollectionModule {}
diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts
new file mode 100644
index 000000000..939fb4981
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts
@@ -0,0 +1,417 @@
+import {
+ Resolver,
+ ResolveField,
+ Parent,
+ Args,
+ Query,
+ Mutation,
+ Subscription,
+ ID,
+} from '@nestjs/graphql';
+import { TeamCollection } from './team-collection.model';
+import { Team, TeamMemberRole } from '../team/team.model';
+import { TeamCollectionService } from './team-collection.service';
+import { GqlAuthGuard } from '../guards/gql-auth.guard';
+import { GqlTeamMemberGuard } from '../team/guards/gql-team-member.guard';
+import { UseGuards } from '@nestjs/common';
+import { RequiresTeamRole } from '../team/decorators/requires-team-role.decorator';
+import { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';
+import { PubSubService } from 'src/pubsub/pubsub.service';
+
+@Resolver(() => TeamCollection)
+export class TeamCollectionResolver {
+ constructor(
+ private readonly teamCollectionService: TeamCollectionService,
+ private readonly pubsub: PubSubService,
+ ) {}
+
+ // Field resolvers
+ @ResolveField(() => Team, {
+ description: 'Team the collection belongs to',
+ complexity: 5,
+ })
+ team(@Parent() collection: TeamCollection): Promise<Team> {
+ return this.teamCollectionService.getTeamOfCollection(collection.id);
+ }
+
+ @ResolveField(() => TeamCollection, {
+ description:
+ 'The collection whom is the parent of this collection (null if this is root collection)',
+ nullable: true,
+ complexity: 3,
+ })
+ parent(@Parent() collection: TeamCollection): Promise<TeamCollection | null> {
+ return this.teamCollectionService.getParentOfCollection(collection.id);
+ }
+
+ @ResolveField(() => [TeamCollection], {
+ description: 'List of children collection',
+ complexity: 3,
+ })
+ children(
+ @Parent() collection: TeamCollection,
+ @Args({
+ name: 'cursor',
+ nullable: true,
+ description: 'ID of the last returned collection (for pagination)',
+ })
+ cursor?: string,
+ ): Promise<TeamCollection[]> {
+ return this.teamCollectionService.getChildrenOfCollection(
+ collection.id,
+ cursor ?? null,
+ );
+ }
+
+ // Queries
+ // @Query(() => String, {
+ // description:
+ // 'Returns the JSON string giving the collections and their contents of the team',
+ // })
+ // @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ // @RequiresTeamRole(
+ // TeamMemberRole.VIEWER,
+ // TeamMemberRole.EDITOR,
+ // TeamMemberRole.OWNER,
+ // )
+ // exportCollectionsToJSON(
+ // @Args({ name: 'teamID', description: 'ID of the team', type: () => ID }) teamID: string,
+ // ): Promise<string> {
+ // return this.teamCollectionService.exportCollectionsToJSON(teamID);
+ // }
+
+ @Query(() => [TeamCollection], {
+ description: 'Returns the collections of the team',
+ })
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ @RequiresTeamRole(
+ TeamMemberRole.VIEWER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.OWNER,
+ )
+ rootCollectionsOfTeam(
+ @Args({ name: 'teamID', description: 'ID of the team', type: () => ID })
+ teamID: string,
+ @Args({
+ name: 'cursor',
+ nullable: true,
+ type: () => ID,
+ description: 'ID of the last returned collection (for pagination)',
+ })
+ cursor?: string,
+ ): Promise<TeamCollection[]> {
+ return this.teamCollectionService.getTeamRootCollections(
+ teamID,
+ cursor ?? null,
+ );
+ }
+
+ @Query(() => [TeamCollection], {
+ description: 'Returns the collections of the team',
+ deprecationReason:
+ 'Deprecated because of no practical use. Use `rootCollectionsOfTeam` instead.',
+ })
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ @RequiresTeamRole(
+ TeamMemberRole.VIEWER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.OWNER,
+ )
+ collectionsOfTeam(
+ @Args({ name: 'teamID', description: 'ID of the team', type: () => ID })
+ teamID: string,
+ @Args({
+ name: 'cursor',
+ type: () => ID,
+ nullable: true,
+ description: 'ID of the last returned collection (for pagination)',
+ })
+ cursor?: string,
+ ): Promise<TeamCollection[]> {
+ return this.teamCollectionService.getTeamCollections(
+ teamID,
+ cursor ?? null,
+ );
+ }
+
+ @Query(() => TeamCollection, {
+ description: 'Get a collection with the given ID or null (if not exists)',
+ nullable: true,
+ })
+ @UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
+ @RequiresTeamRole(
+ TeamMemberRole.VIEWER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.OWNER,
+ )
+ collection(
+ @Args({
+ name: 'collectionID',
+ description: 'ID of the collection',
+ type: () => ID,
+ })
+ collectionID: string,
+ ): Promise<TeamCollection | null> {
+ return this.teamCollectionService.getCollection(collectionID);
+ }
+
+ // Mutations
+ @Mutation(() => TeamCollection, {
+ description:
+ 'Creates a collection at the root of the team hierarchy (no parent collection)',
+ })
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ createRootCollection(
+ @Args({ name: 'teamID', description: 'ID of the team', type: () => ID })
+ teamID: string,
+ @Args({ name: 'title', description: 'Title of the new collection' })
+ title: string,
+ ): Promise<TeamCollection> {
+ return this.teamCollectionService.createCollection(teamID, title, null);
+ }
+
+ // @Mutation(() => TeamCollection, {
+ // description: 'Import collection from user firestore',
+ // })
+ // @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ // @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ // importCollectionFromUserFirestore(
+ // @Args({
+ // name: 'teamID',
+ // type: () => ID,
+ // description: 'ID of the team to add to',
+ // })
+ // teamID: string,
+ // @Args({
+ // name: 'fbCollectionPath',
+ // description:
+ // 'slash separated array indicies path to the target collection',
+ // })
+ // fbCollectionPath: string,
+ // @GqlUser() user: User,
+ // @Args({
+ // name: 'parentCollectionID',
+ // type: () => ID,
+ // description:
+ // 'ID to the collection which is going to be parent to the result (null if root)',
+ // nullable: true,
+ // })
+ // parentCollectionID?: string
+ // ): Promise<TeamCollection> {
+ // if (parentCollectionID) {
+ // return this.teamCollectionService.importCollectionFromFirestore(
+ // user.uid,
+ // fbCollectionPath,
+ // teamID,
+ // parentCollectionID,
+ // );
+ // } else {
+ // return this.teamCollectionService.importCollectionFromFirestore(
+ // user.uid,
+ // fbCollectionPath,
+ // teamID,
+ // );
+ // }
+ // }
+
+ // @Mutation(() => Boolean, {
+ // description: 'Import collections from JSON string to the specified Team',
+ // })
+ // @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ // @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ // async importCollectionsFromJSON(
+ // @Args({
+ // name: 'teamID',
+ // type: () => ID,
+ // description: 'Id of the team to add to',
+ // })
+ // teamID: string,
+ // @Args({
+ // name: 'jsonString',
+ // description: 'JSON string to import',
+ // })
+ // jsonString: string,
+ // @Args({
+ // name: 'parentCollectionID',
+ // type: () => ID,
+ // description:
+ // 'ID to the collection to which to import to (null if to import to the root of team)',
+ // nullable: true,
+ // })
+ // parentCollectionID?: string,
+ // ): Promise<boolean> {
+ // await this.teamCollectionService.importCollectionsFromJSON(
+ // jsonString,
+ // teamID,
+ // parentCollectionID ?? null,
+ // );
+
+ // return true;
+ // }
+
+ // @Mutation(() => Boolean, {
+ // description:
+ // 'Replace existing collections of a specific team with collections in JSON string',
+ // })
+ // @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ // @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ // async replaceCollectionsWithJSON(
+ // @Args({
+ // name: 'teamID',
+ // type: () => ID,
+ // description: 'Id of the team to add to',
+ // })
+ // teamID: string,
+ // @Args({
+ // name: 'jsonString',
+ // description: 'JSON string to replace with',
+ // })
+ // jsonString: string,
+ // @Args({
+ // name: 'parentCollectionID',
+ // type: () => ID,
+ // description:
+ // 'ID to the collection to which to import to (null if to import to the root of team)',
+ // nullable: true,
+ // })
+ // parentCollectionID?: string,
+ // ): Promise<boolean> {
+ // await this.teamCollectionService.replaceCollectionsWithJSON(
+ // jsonString,
+ // teamID,
+ // parentCollectionID ?? null,
+ // );
+
+ // return true;
+ // }
+
+ @Mutation(() => TeamCollection, {
+ description: 'Create a collection that has a parent collection',
+ })
+ @UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
+ @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ async createChildCollection(
+ @Args({
+ name: 'collectionID',
+ type: () => ID,
+ description: 'ID of the parent to the new collection',
+ })
+ collectionID: string,
+ @Args({ name: 'childTitle', description: 'Title of the new collection' })
+ childTitle: string,
+ ): Promise<TeamCollection> {
+ const team = await this.teamCollectionService.getTeamOfCollection(
+ collectionID,
+ );
+ return await this.teamCollectionService.createCollection(
+ team.id,
+ childTitle,
+ collectionID,
+ );
+ }
+
+ @Mutation(() => TeamCollection, {
+ description: 'Rename a collection',
+ })
+ @UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
+ @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ renameCollection(
+ @Args({
+ name: 'collectionID',
+ description: 'ID of the collection',
+ type: () => ID,
+ })
+ collectionID: string,
+ @Args({
+ name: 'newTitle',
+ description: 'The updated title of the collection',
+ })
+ newTitle: string,
+ ): Promise<TeamCollection> {
+ return this.teamCollectionService.renameCollection(collectionID, newTitle);
+ }
+
+ @Mutation(() => Boolean, {
+ description: 'Delete a collection',
+ })
+ @UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
+ @RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
+ async deleteCollection(
+ @Args({
+ name: 'collectionID',
+ description: 'ID of the collection',
+ type: () => ID,
+ })
+ collectionID: string,
+ ): Promise<boolean> {
+ this.teamCollectionService.deleteCollection(collectionID);
+
+ return true;
+ }
+
+ // Subscriptions
+ @Subscription(() => TeamCollection, {
+ description:
+ 'Listen to when a collection has been added to a team. The emitted value is the team added',
+ resolve: (value) => value,
+ })
+ @RequiresTeamRole(
+ TeamMemberRole.OWNER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.VIEWER,
+ )
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ teamCollectionAdded(
+ @Args({
+ name: 'teamID',
+ description: 'ID of the team to listen to',
+ type: () => ID,
+ })
+ teamID: string,
+ ): AsyncIterator<TeamCollection> {
+ return this.pubsub.asyncIterator(`team_coll/${teamID}/coll_added`);
+ }
+
+ @Subscription(() => TeamCollection, {
+ description: 'Listen to when a collection has been updated.',
+ resolve: (value) => value,
+ })
+ @RequiresTeamRole(
+ TeamMemberRole.OWNER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.VIEWER,
+ )
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ teamCollectionUpdated(
+ @Args({
+ name: 'teamID',
+ description: 'ID of the team to listen to',
+ type: () => ID,
+ })
+ teamID: string,
+ ): AsyncIterator<TeamCollection> {
+ return this.pubsub.asyncIterator(`team_coll/${teamID}/coll_updated`);
+ }
+
+ @Subscription(() => ID, {
+ description: 'Listen to when a collection has been removed',
+ resolve: (value) => value,
+ })
+ @RequiresTeamRole(
+ TeamMemberRole.OWNER,
+ TeamMemberRole.EDITOR,
+ TeamMemberRole.VIEWER,
+ )
+ @UseGuards(GqlAuthGuard, GqlTeamMemberGuard)
+ teamCollectionRemoved(
+ @Args({
+ name: 'teamID',
+ description: 'ID of the team to listen to',
+ type: () => ID,
+ })
+ teamID: string,
+ ): AsyncIterator<TeamCollection> {
+ return this.pubsub.asyncIterator(`team_coll/${teamID}/coll_removed`);
+ }
+}
diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts
new file mode 100644
index 000000000..16c6e88aa
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts
@@ -0,0 +1,1933 @@
+import { TeamCollectionService } from './team-collection.service';
+import { PrismaService } from '../prisma/prisma.service';
+import { TeamCollection } from './team-collection.model';
+import {
+ TEAM_USER_NO_FB_SYNCDATA,
+ TEAM_FB_COLL_PATH_RESOLVE_FAIL,
+ TEAM_COLL_INVALID_JSON,
+ TEAM_INVALID_COLL_ID,
+} from '../errors';
+import { mockDeep, mockReset } from 'jest-mock-extended';
+
+const mockPrisma = mockDeep<PrismaService>();
+
+const mockDocFunc = jest.fn();
+
+const mockFB = {
+ firestore: {
+ doc: mockDocFunc,
+ },
+};
+
+const mockPubSub = {
+ publish: jest.fn().mockResolvedValue(null),
+};
+
+const teamCollectionService = new TeamCollectionService(
+ mockPrisma,
+ mockFB as any,
+ mockPubSub as any,
+);
+
+beforeEach(() => {
+ mockPubSub.publish.mockClear();
+ mockReset(mockPrisma);
+});
+
+// TODO: rewrite tests for importCollectionsFromJSON and replaceCollectionsWithJSON
+describe('exportCollectionsToJSON', () => {
+ test('resolves with the correct collection info', async () => {
+ /**
+ * Imagine a team with collections of this format
+ *
+ * (id)
+ * Collection1 {
+ * Request1 { "name": "dev.to homepage", "url": "https://dev.to"}
+ * Collection2 {
+ * Request2 { "name": "dev.to homepage", "url": "https://dev.to"}
+ * }
+ * }
+ */
+ const testCollectionsJSON = `
+ [{
+ "folders": [{
+ "folders": [],
+ "name": "Collection2",
+ "requests": [{
+ "name": "dev.to homepage",
+ "url": "https://dev.to"
+ }]
+ }],
+ "name": "Collection1",
+ "requests": [{
+ "name": "dev.to homepage",
+ "url": "https://dev.to"
+ }]
+ }]
+ `;
+ mockPrisma.teamCollection.findMany.mockImplementation((query) => {
+ if (query?.where?.parentID === null) {
+ return Promise.resolve([
+ {
+ prisma: true,
+ id: 'Collection1',
+ title: 'Collection1',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]) as any;
+ } else if (query?.where?.parentID === 'Collection1') {
+ return Promise.resolve([
+ {
+ prisma: true,
+ id: 'Collection2',
+ title: 'Collection2',
+ parentID: 'Collection1',
+ teamID: '3170',
+ },
+ ]);
+ } else {
+ return Promise.resolve([]);
+ }
+ });
+
+ mockPrisma.teamCollection.findUnique.mockImplementation((query) => {
+ if (query?.where?.id === 'Collection1') {
+ return Promise.resolve({
+ prisma: true,
+ id: 'Collection1',
+ title: 'Collection1',
+ parentID: null,
+ teamID: '3170',
+ });
+ } else if (query?.where?.id === 'Collection2') {
+ return Promise.resolve({
+ prisma: true,
+ id: 'Collection2',
+ title: 'Collection2',
+ parentID: 'Collection1',
+ teamID: '3170',
+ });
+ } else {
+ return Promise.reject('RecordNotFound') as any;
+ }
+ });
+
+ mockPrisma.teamRequest.findMany.mockImplementation((query) => {
+ if (query?.where?.collectionID === 'Collection1') {
+ return Promise.resolve([
+ {
+ prisma: true,
+ id: 'Request1',
+ collectionID: 'Collection1',
+ title: 'Request1',
+ request: {
+ url: 'https://dev.to',
+ name: 'dev.to homepage',
+ },
+ teamID: '3170',
+ },
+ ]) as any;
+ } else if (query?.where?.collectionID === 'Collection2') {
+ return Promise.resolve([
+ {
+ prisma: true,
+ id: 'Request2',
+ collectionID: 'Collection2',
+ title: 'Request2',
+ request: {
+ url: 'https://dev.to',
+ name: 'dev.to homepage',
+ },
+ teamID: '3170',
+ },
+ ]);
+ } else {
+ return Promise.resolve([]);
+ }
+ });
+
+ expect(
+ JSON.parse(await teamCollectionService.exportCollectionsToJSON('3170')),
+ ).toEqual(JSON.parse(testCollectionsJSON));
+ });
+});
+
+describe('importCollectionFromFirestore', () => {
+ test('rejects if called when the user has no synced collection data with TEAM_USER_NO_FB_SYNCDATA', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: false,
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue(null as any);
+
+ await expect(
+ teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0/0',
+ '3170',
+ ),
+ ).rejects.toThrowError(TEAM_USER_NO_FB_SYNCDATA);
+ expect(mockPrisma.teamCollection.create).not.toHaveBeenCalled();
+ });
+
+ test('rejects if called with the collection path is invalid with TEAM_FB_COLL_PATH_RESOLVE_FAIL', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue(null as any);
+
+ await expect(
+ teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0/0',
+ '3170',
+ ),
+ ).rejects.toThrowError(TEAM_FB_COLL_PATH_RESOLVE_FAIL);
+ expect(mockPrisma.teamCollection.create).not.toHaveBeenCalled();
+ });
+
+ test('resolves with proper collection path for single level nesting and updates the database', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ } as any);
+
+ await expect(
+ teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0',
+ '3170',
+ ),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test('resolves with proper collection path for single level nesting and fires the pubsub "team_coll/<team_id>/coll_added" subject', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ } as any);
+
+ const result = await teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0',
+ '3170',
+ );
+
+ expect(mockPubSub.publish).toBeCalledWith(
+ 'team_coll/3170/coll_added',
+ result,
+ );
+ });
+
+ test('resolves with proper collection path for multi level nesting and updates the database with hierarachy', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [
+ {
+ folders: [],
+ name: 'Test Subfolder',
+ requests: [
+ { name: 'Test Sub 1 1' },
+ { name: 'Test Sub 2 2' },
+ ],
+ },
+ ],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ children: [
+ {
+ id: 'testchilduid1',
+ title: 'Test Subfolder',
+ parentID: 'testuid1',
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test Sub 1 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 1 1"}',
+ },
+ {
+ title: 'Test Sub 2 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 2 2"}',
+ },
+ ],
+ },
+ ],
+ } as any);
+
+ await expect(
+ teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0',
+ '3170',
+ ),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test('resolves with proper collection path for multi level nesting and fires the pubsub "team_coll/3170/coll_added" topic', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [
+ {
+ folders: [],
+ name: 'Test Subfolder',
+ requests: [
+ { name: 'Test Sub 1 1' },
+ { name: 'Test Sub 2 2' },
+ ],
+ },
+ ],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ children: [
+ {
+ id: 'testchilduid1',
+ title: 'Test Subfolder',
+ parentID: 'testuid1',
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test Sub 1 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 1 1"}',
+ },
+ {
+ title: 'Test Sub 2 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 2 2"}',
+ },
+ ],
+ },
+ ],
+ } as any);
+
+ const result = await teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0',
+ '3170',
+ );
+
+ expect(mockPubSub.publish).toHaveBeenCalledWith(
+ 'team_coll/3170/coll_added',
+ result,
+ );
+ });
+
+ test('when no parentCollectionID is specified (or null) the collection is created at root of team collection hierarachy', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [
+ {
+ folders: [],
+ name: 'Test Subfolder',
+ requests: [
+ { name: 'Test Sub 1 1' },
+ { name: 'Test Sub 2 2' },
+ ],
+ },
+ ],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ children: [
+ {
+ id: 'testchilduid1',
+ title: 'Test Subfolder',
+ parentID: 'testuid1',
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test Sub 1 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 1 1"}',
+ },
+ {
+ title: 'Test Sub 2 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 2 2"}',
+ },
+ ],
+ },
+ ],
+ } as any);
+
+ const result = await teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0',
+ '3170',
+ );
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ title: 'Test',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test('when parentCollectionID is specified the collection is created at the corresponding location', async () => {
+ mockDocFunc.mockReturnValueOnce({
+ get: jest.fn().mockResolvedValue({
+ exists: true,
+ data: () => {
+ return {
+ collection: [
+ {
+ folders: [
+ {
+ folders: [],
+ name: 'Test Subfolder',
+ requests: [
+ { name: 'Test Sub 1 1' },
+ { name: 'Test Sub 2 2' },
+ ],
+ },
+ ],
+ name: 'Test',
+ requests: [{ name: 'Test 1' }, { name: 'Test 2' }],
+ },
+ ],
+ };
+ },
+ }),
+ });
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testcoll1',
+ title: 'Test Coll 1',
+ parentID: null,
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ } as any);
+
+ const parentCollection = await teamCollectionService.createCollection(
+ '3170',
+ 'Test Coll 1',
+ null,
+ );
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testuid1',
+ title: 'Test',
+ parentID: 'testcoll1',
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 1"}',
+ },
+ {
+ title: 'Test 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test 2"}',
+ },
+ ],
+ children: [
+ {
+ id: 'testchilduid1',
+ title: 'Test Subfolder',
+ parentID: 'testuid1',
+ teamID: '3170',
+ requests: [
+ {
+ title: 'Test Sub 1 1',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 1 1"}',
+ },
+ {
+ title: 'Test Sub 2 2',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ request: '{ name: "Test Sub 2 2"}',
+ },
+ ],
+ },
+ ],
+ parent: {
+ prisma: true,
+ id: 'testcoll1',
+ title: 'Test Coll 1',
+ parentID: null,
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Team 1',
+ },
+ },
+ } as any);
+
+ await expect(
+ teamCollectionService.importCollectionFromFirestore(
+ 'testuid1',
+ '0/0',
+ '3170',
+ parentCollection.id,
+ ),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ title: 'Test',
+ parentID: parentCollection.id,
+ teamID: '3170',
+ }),
+ );
+ });
+});
+
+describe('createCollection', () => {
+ test('rejects if null team id', async () => {
+ mockPrisma.teamCollection.create.mockRejectedValue(null as any);
+
+ await expect(
+ teamCollectionService.createCollection(null as any, 'Test Coll 2', null),
+ ).rejects.toBeDefined();
+ });
+
+ test('rejects if invalid teamID', async () => {
+ mockPrisma.teamCollection.create.mockRejectedValue(null as any);
+
+ await expect(
+ teamCollectionService.createCollection(
+ 'invalidteamid',
+ 'Test Coll 2',
+ null,
+ ),
+ ).rejects.toBeDefined();
+ });
+
+ test('rejects if short title', async () => {
+ mockPrisma.teamCollection.create.mockRejectedValue(null as any);
+
+ await expect(
+ teamCollectionService.createCollection('3170', 'Te', null),
+ ).rejects.toBeDefined();
+ expect(mockPrisma.teamCollection.create).not.toHaveBeenCalled();
+ });
+
+ test('resolves if valid team id and title with null parentID', async () => {
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 2',
+ parentID: null,
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Test Team 1',
+ },
+ } as any);
+
+ await expect(
+ teamCollectionService.createCollection('3170', 'Test Collection 2', null),
+ ).resolves.toBeDefined();
+ });
+
+ test('rejects if valid team id and title with invalid parentID', async () => {
+ mockPrisma.teamCollection.create.mockRejectedValue(null as any);
+
+ await expect(
+ teamCollectionService.createCollection(
+ '3170',
+ 'Test Child Collection 1',
+ 'invalidtestcoll',
+ ),
+ ).rejects.toBeDefined();
+ });
+
+ test('resolves if valid team id and title with valid parentID', async () => {
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testchildcoll',
+ title: 'Test Collection 2',
+ parentID: 'testcoll',
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Test Team 1',
+ },
+ parent: {
+ id: 'testcoll',
+ title: 'Test Collection 3',
+ parentID: null,
+ teamID: '3170',
+ },
+ } as any);
+
+ await expect(
+ teamCollectionService.createCollection(
+ '3170',
+ 'Test Child Collection 1',
+ 'testcoll',
+ ),
+ ).resolves.toBeDefined();
+ });
+
+ test('publishes creation to pubsub topic "team_coll/<team_id>/coll_added"', async () => {
+ const result = await teamCollectionService.createCollection(
+ '3170',
+ 'Test Child Collection 1',
+ 'testcoll',
+ );
+
+ mockPrisma.teamCollection.create.mockResolvedValue({
+ id: 'testchildcoll',
+ title: 'Test Collection 1',
+ parentID: 'testcoll',
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Test Team 1',
+ },
+ parent: {
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ },
+ } as any);
+
+ expect(mockPubSub.publish).toHaveBeenCalledWith(
+ 'team_coll/3170/coll_added',
+ result,
+ );
+ });
+});
+
+describe('deleteCollection', () => {
+ test('resolves if the collection id is valid', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ mockPrisma.teamRequest.deleteMany.mockResolvedValue({
+ count: 0,
+ });
+
+ mockPrisma.teamCollection.delete.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ await expect(
+ teamCollectionService.deleteCollection('testcoll'),
+ ).resolves.toBeUndefined();
+ });
+
+ test('rejects if the collection id is not valid', async () => {
+ mockPrisma.teamCollection.findUnique.mockRejectedValue(
+ TEAM_INVALID_COLL_ID,
+ );
+
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ mockPrisma.teamRequest.deleteMany.mockResolvedValue({
+ count: 0,
+ });
+
+ mockPrisma.teamCollection.delete.mockResolvedValue(null as any);
+
+ await expect(
+ teamCollectionService.deleteCollection('invalidtestcoll'),
+ ).rejects.toBeDefined();
+
+ expect(mockPrisma.teamCollection.findMany).not.toHaveBeenCalled();
+
+ expect(mockPrisma.teamCollection.deleteMany).not.toHaveBeenCalled();
+
+ expect(mockPrisma.teamCollection.delete).not.toHaveBeenCalled();
+ });
+
+ test('performs the deletion on the database', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ mockPrisma.teamRequest.deleteMany.mockResolvedValue({
+ count: 0,
+ });
+
+ mockPrisma.teamCollection.delete.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ await teamCollectionService.deleteCollection('testcoll');
+
+ expect(mockPrisma.teamCollection.delete).toHaveBeenCalledWith({
+ where: {
+ id: 'testcoll',
+ },
+ });
+ });
+
+ test('publishes to pubsub topic "team_coll/<team_id>/coll_removed"', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ mockPrisma.teamRequest.deleteMany.mockResolvedValue({
+ count: 0,
+ });
+
+ mockPrisma.teamCollection.delete.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ await teamCollectionService.deleteCollection('testcoll');
+
+ expect(mockPubSub.publish).toHaveBeenCalledWith(
+ 'team_coll/3170/coll_removed',
+ 'testcoll',
+ );
+ });
+});
+
+describe('getCollection', () => {
+ test('resolves with the valid collection info for valid collection id', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ await expect(
+ teamCollectionService.getCollection('testcoll'),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test("resolves with null if the collection id doesn't exist", async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue(null as any);
+
+ await expect(
+ teamCollectionService.getCollection('invalidtestcoll'),
+ ).resolves.toBeNull();
+ });
+});
+
+describe('renameCollection', () => {
+ test('rejects if the new title has length less than 3', async () => {
+ mockPrisma.teamCollection.update.mockRejectedValue(null as any);
+
+ await expect(
+ teamCollectionService.renameCollection('testcoll', 'Te'),
+ ).rejects.toBeDefined();
+ expect(mockPrisma.teamCollection.update).not.toHaveBeenCalled();
+ });
+
+ test("rejects if the collection id doesn't exist", async () => {
+ mockPrisma.teamCollection.update.mockRejectedValue('RecordNotFound');
+
+ await expect(
+ teamCollectionService.renameCollection(
+ 'invalidtestcoll',
+ 'Test Coll rename',
+ ),
+ ).rejects.toBeDefined();
+ });
+
+ test('valid queries resolves with the updated team collection', async () => {
+ mockPrisma.teamCollection.update.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Rename 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ await expect(
+ teamCollectionService.renameCollection('testcoll', 'Test Rename 1'),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: 'testcoll',
+ title: 'Test Rename 1',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test('publish pubsub topic "team_coll/<team_id>/coll_updated"', async () => {
+ mockPrisma.teamCollection.update.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Rename 1',
+ parentID: null,
+ teamID: '3170',
+ });
+
+ const member = await teamCollectionService.renameCollection(
+ 'testcoll',
+ 'Test Rename 1',
+ );
+
+ expect(mockPubSub.publish).toHaveBeenCalledWith(
+ 'team_coll/3170/coll_updated',
+ member,
+ );
+ });
+});
+
+describe('getTeamOfCollection', () => {
+ test('resolves with the correct team info if valid info is given', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: '3170',
+ title: 'Test Collection',
+ parentID: null,
+ teamID: '3170',
+ team: {
+ id: '3170',
+ name: 'Test Team',
+ },
+ } as any);
+
+ await expect(
+ teamCollectionService.getTeamOfCollection('testcoll'),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: '3170',
+ name: 'Test Team',
+ }),
+ );
+ });
+
+ test("rejects if the collection id doesn't exist", async () => {
+ mockPrisma.teamCollection.findUnique.mockRejectedValue('RecordNotFound');
+
+ await expect(
+ teamCollectionService.getTeamOfCollection('invalidtestcoll'),
+ ).rejects.toBeDefined();
+ });
+});
+
+describe('getParentOfCollection', () => {
+ test('resolves to null if the collection exists but no parent', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll',
+ title: 'Test Collection 1',
+ parentID: null,
+ teamID: '3170',
+ parent: null,
+ } as any);
+
+ await expect(
+ teamCollectionService.getParentOfCollection('testcoll'),
+ ).resolves.toBeNull();
+ });
+
+ test('resolves with the parent info if the collection exists and has parent', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValue({
+ id: 'testcoll1',
+ title: 'Test Collection 1',
+ parentID: 'testparent',
+ teamID: '3170',
+ parent: {
+ id: 'testcoll2',
+ title: 'Test Collection 2',
+ parentID: null,
+ teamID: '3170',
+ },
+ } as any);
+
+ await expect(
+ teamCollectionService.getParentOfCollection('testcoll2'),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ id: 'testcoll2',
+ title: 'Test Collection 2',
+ parentID: null,
+ teamID: '3170',
+ }),
+ );
+ });
+
+ test("rejects if the collection id doesn't exist", async () => {
+ mockPrisma.teamCollection.findUnique.mockRejectedValue('RecordNotFound');
+
+ await expect(
+ teamCollectionService.getParentOfCollection('invalidtestcoll'),
+ ).rejects.toBeDefined();
+ });
+});
+
+describe('getChildrenOfCollection', () => {
+ test('resolves for valid collection id and null cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getChildrenOfCollection('testcoll', null),
+ ).resolves.toBeDefined();
+ });
+
+ test('resolves for invalid collection id and null cursor with an empty array', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getChildrenOfCollection('invalidcollid', null),
+ ).resolves.toHaveLength(0);
+ });
+
+ test('resolves for valid collection id and non-null invalid cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getChildrenOfCollection(
+ 'testcoll',
+ 'invalidcursor',
+ ),
+ ).resolves.toBeDefined();
+ });
+
+ test('returns the first 10 elements only for valid collection id and null cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'testcoll',
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getChildrenOfCollection('testcoll', null),
+ ).resolves.toHaveLength(10);
+ });
+
+ test('returns the 10 elements only for valid collection id and valid cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ ]);
+
+ const secondChildColl = (
+ await teamCollectionService.getChildrenOfCollection('someid', null)
+ )[1];
+
+ mockReset(mockPrisma);
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid11',
+ title: 'testcoll11',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid12',
+ title: 'testcoll12',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid13',
+ title: 'testcoll13',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid14',
+ title: 'testcoll14',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid15',
+ title: 'testcoll15',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid16',
+ title: 'testcoll16',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid17',
+ title: 'testcoll17',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid18',
+ title: 'testcoll18',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid19',
+ title: 'testcoll19',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ {
+ id: 'someid20',
+ title: 'testcoll20',
+ parentID: 'someid',
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getChildrenOfCollection(
+ 'someid',
+ secondChildColl.id,
+ ),
+ ).resolves.toHaveLength(10);
+ });
+});
+
+describe('getTeamRootCollections', () => {
+ test('resolves for valid team id and null cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getTeamRootCollections('3170', null),
+ ).resolves.toBeDefined();
+ });
+
+ test('resolves for invalid team id and null cursor with an empty array', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getTeamRootCollections('invalidteamid', null),
+ ).resolves.toHaveLength(0);
+ });
+
+ test('resolves for valid team id and null cursor with the first 10 elements', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]);
+
+ return expect(
+ teamCollectionService.getTeamRootCollections('3170', null),
+ ).resolves.toHaveLength(10);
+ });
+
+ test('resolves for valid team id and invalid cursor with empty array', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getTeamRootCollections('3170', 'invalidcursor'),
+ ).resolves.toHaveLength(0);
+ });
+
+ test('resolves for valid team id and valid cursor with the next 10 elements', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]);
+
+ const secondColl = (
+ await teamCollectionService.getTeamRootCollections('3170', null)
+ )[1];
+
+ mockReset(mockPrisma);
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid11',
+ title: 'testcoll11',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid12',
+ title: 'testcoll12',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid13',
+ title: 'testcoll13',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid14',
+ title: 'testcoll14',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid15',
+ title: 'testcoll15',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid17',
+ title: 'testcoll17',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid18',
+ title: 'testcoll18',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid19',
+ title: 'testcoll19',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid20',
+ title: 'testcoll20',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getTeamRootCollections('3170', secondColl.id),
+ ).resolves.toHaveLength(10);
+ });
+});
+
+describe('getTeamCollections', () => {
+ test('resolves for valid team id and null cursor', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getTeamCollections('3170', null),
+ ).resolves.toBeDefined();
+ });
+
+ test('resolves for invalid team id and null cursor with an empty array', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getTeamCollections('invalidteamid', null),
+ ).resolves.toHaveLength(0);
+ });
+
+ test('resolves for valid team id and null cursor with the first 10 elements', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'someid1',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'someid3',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'someid5',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'someid7',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'someid9',
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getTeamCollections('3170', null),
+ ).resolves.toHaveLength(10);
+ });
+
+ test('resolves for valid team id and invalid cursor with empty array', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([]);
+
+ await expect(
+ teamCollectionService.getTeamCollections('3170', 'invalidcursor'),
+ ).resolves.toHaveLength(0);
+ });
+
+ test('resolves for valid team id and valid cursor with the next 10 elements', async () => {
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'someid1',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'someid3',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'someid5',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'someid7',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'someid9',
+ teamID: '3170',
+ },
+ ]);
+
+ const secondColl = (
+ await teamCollectionService.getTeamCollections('3170', null)
+ )[1];
+
+ mockReset(mockPrisma);
+ mockPrisma.teamCollection.findMany.mockResolvedValue([
+ {
+ id: 'someid1',
+ title: 'testcoll1',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid2',
+ title: 'testcoll2',
+ parentID: 'someid1',
+ teamID: '3170',
+ },
+ {
+ id: 'someid3',
+ title: 'testcoll3',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid4',
+ title: 'testcoll4',
+ parentID: 'someid3',
+ teamID: '3170',
+ },
+ {
+ id: 'someid5',
+ title: 'testcoll5',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid6',
+ title: 'testcoll6',
+ parentID: 'someid5',
+ teamID: '3170',
+ },
+ {
+ id: 'someid7',
+ title: 'testcoll7',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid8',
+ title: 'testcoll8',
+ parentID: 'someid7',
+ teamID: '3170',
+ },
+ {
+ id: 'someid9',
+ title: 'testcoll9',
+ parentID: null,
+ teamID: '3170',
+ },
+ {
+ id: 'someid10',
+ title: 'testcoll10',
+ parentID: 'someid9',
+ teamID: '3170',
+ },
+ ]);
+
+ await expect(
+ teamCollectionService.getTeamCollections('3170', secondColl.id),
+ ).resolves.toHaveLength(10);
+ });
+
+ describe('getCollectionTO', () => {
+ test('should resolve to Some for valid collection ID', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce({
+ id: 'testcoll',
+ parentID: 'testparentcoll',
+ teamID: '3170',
+ title: 'Test Collection',
+ });
+
+ expect(
+ await teamCollectionService.getCollectionTO('testcoll')(),
+ ).toBeSome();
+ });
+
+ test('should resolve to the correct Some value for a valid collection ID', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce({
+ id: 'testcoll',
+ parentID: 'testparentcoll',
+ teamID: '3170',
+ title: 'Test Collection',
+ });
+
+ expect(
+ await teamCollectionService.getCollectionTO('testcoll')(),
+ ).toEqualSome(<TeamCollection>{
+ id: 'testcoll',
+ parentID: 'testparentcoll',
+ teamID: '3170',
+ title: 'Test Collection',
+ });
+ });
+
+ test('should resolve a None value if the the collection ID does not exist', async () => {
+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce(null);
+
+ expect(
+ await teamCollectionService.getCollectionTO('testcoll')(),
+ ).toBeNone();
+ });
+ });
+});
diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts
new file mode 100644
index 000000000..5e8f71567
--- /dev/null
+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts
@@ -0,0 +1,509 @@
+import { Injectable } from '@nestjs/common';
+import { PrismaService } from '../prisma/prisma.service';
+import { Team } from '../team/team.model';
+import { TeamCollection } from './team-collection.model';
+// import { FirebaseService } from '../firebase/firebase.service';
+import {
+ TEAM_USER_NO_FB_SYNCDATA,
+ TEAM_FB_COLL_PATH_RESOLVE_FAIL,
+ TEAM_COLL_SHORT_TITLE,
+ TEAM_COLL_INVALID_JSON,
+ TEAM_INVALID_COLL_ID,
+} from '../errors';
+import { PubSubService } from '../pubsub/pubsub.service';
+import { throwErr } from 'src/utils';
+import { pipe } from 'fp-ts/function';
+import * as TO from 'fp-ts/TaskOption';
+
+@Injectable()
+export class TeamCollectionService {
+ constructor(
+ private readonly prisma: PrismaService,
+ // private readonly fb: FirebaseService,
+ private readonly pubsub: PubSubService,
+ ) {}
+
+ // TODO: Change return type
+ // private generatePrismaQueryObjForFBCollFolder(
+ // folder: FBCollectionFolder,
+ // teamID: string,
+ // ): any {
+ // return {
+ // title: folder.name,
+ // team: {
+ // connect: {
+ // id: teamID,
+ // },
+ // },
+ // requests: {
+ // create: folder.requests.map((r) => ({
+ // title: r.name,
+ // team: {
+ // connect: {
+ // id: teamID,
+ // },
+ // },
+ // request: r,
+ // })),
+ // },
+ // children: {
+ // create: folder.folders.map((f) =>
+ // this.generatePrismaQueryObjForFBCollFolder(f, teamID),
+ // ),
+ // },
+ // };
+ // }
+
+ // async importCollectionFromFirestore(
+ // userUid: string,
+ // fbCollectionPath: string,
+ // teamID: string,
+ // parentCollectionID?: string,
+ // ): Promise<TeamCollection> {
+ // const syncDoc = await this.fb.firestore
+ // .doc(`users/${userUid}/collections/sync`)
+ // .get();
+
+ // if (!syncDoc.exists) throw new Error(TEAM_USER_NO_FB_SYNCDATA);
+
+ // const doc = syncDoc.data();
+
+ // if (!doc) throw new Error(TEAM_USER_NO_FB_SYNCDATA);
+
+ // // The 'target' variable will have the intended path to reach
+ // let target: FBCollectionFolder | null | undefined;
+ // try {
+ // const indexPaths = fbCollectionPath.split('/').map((x) => parseInt(x));
+ // target = doc.collection[indexPaths.shift() as number];
+ // while (indexPaths.length > 0)
+ // {
+ // const index = indexPaths.shift() as number;
+ // target = target?.folders[index];
+ // }
+ // } catch (e) {
+ // target = null;
+ // }
+
+ // if (!target) throw new Error(TEAM_FB_COLL_PATH_RESOLVE_FAIL);
+
+ // const queryGen = this.generatePrismaQueryObjForFBCollFolder(target, teamID);
+
+ // let result: TeamCollection;
+
+ // if (parentCollectionID) {
+ // result = await this.prisma.teamCollection.create({
+ // data: {
+ // ...queryGen,
+ // parent: {
+ // connect: {
+ // id: parentCollectionID,
+ // },
+ // },
+ // },
+ // });
+ // } else {
+ // result = await this.prisma.teamCollection.create({
+ // data: queryGen,
+ // });
+ // }
+
+ // this.pubsub.publish(`team_coll/${teamID}/coll_added`, result);
+
+ // return result;
+ // }
+
+ // private async exportCollectionToJSONObject(
+ // teamID: string,
+ // collectionID: string,
+ // ): Promise<FBCollectionFolder> {
+ // const collection = await this.getCollection(collectionID);
+
+ // if (!collection) throw new Error(TEAM_INVALID_COLL_ID)
+
+ // const childrenCollection = await this.prisma.teamCollection.findMany({
+ // where: {
+ // teamID,
+ // parentID: collectionID,
+ // },
+ // });
+
+ // const childrenCollectionObjects = await Promise.all(
+ // childrenCollection.map((coll) =>
+ // this.exportCollectionToJSONObject(teamID, coll.id),
+ // ),
+ // );
+
+ // const requests = await this.prisma.teamRequest.findMany({
+ // where: {
+ // teamID,
+ // collectionID,
+ // },
+ // });
+
+ // return {
+ // name: collection.title,
+ // folders: childrenCollectionObjects,
+ // requests: requests.map((x) => x.request),
+ // };
+ // }
+
+ // async exportCollectionsToJSON(teamID: string): Promise<string> {
+ // const rootCollections = await this.prisma.teamCollection.findMany({
+ // where: {
+ // teamID,
+ // parentID: null,
+ // },
+ // });
+
+ // const rootCollectionObjects = await Promise.all(
+ // rootCollections.map((coll) =>
+ // this.exportCollectionToJSONObject(teamID, coll.id),
+ // ),
+ // );
+
+ // return JSON.stringify(rootCollectionObjects);
+ // }
+
+ // async importCollectionsFromJSON(
+ // jsonString: string,
+ // destTeamID: string,
+ // destCollectionID: string | null,
+ // ): Promise<void> {
+ // let collectionsList: FBCollectionFolder[];
+
+ // try {
+ // collectionsList = JSON.parse(jsonString);
+
+ // if (!Array.isArray(collectionsList))
+ // throw new Error(TEAM_COLL_INVALID_JSON);
+ // } catch (e) {
+ // throw new Error(TEAM_COLL_INVALID_JSON);
+ // }
+
+ // const queryList = collectionsList.map((x) =>
+ // this.generatePrismaQueryObjForFBCollFolder(x, destTeamID),
+ // );
+
+ // let requests: TeamCollection[];
+
+ // if (destCollectionID) {
+ // requests = await this.prisma.$transaction(
+ // queryList.map((x) =>
+ // this.prisma.teamCollection.create({
+ // data: {
+ // ...x,
+ // parent: {
+ // connect: {
+ // id: destCollectionID,
+ // },
+ // },
+ // },
+ // }),
+ // ),
+ // );
+ // } else {
+ // requests = await this.prisma.$transaction(
+ // queryList.map((x) =>
+ // this.prisma.teamCollection.create({
+ // data: {
+ // ...x,
+ // },
+ // }),
+ // ),
+ // );
+ // }
+
+ // requests.forEach((x) =>
+ // this.pubsub.publish(`team_coll/${destTeamID}/coll_added`, x),
+ // );
+ // }
+
+ // async replaceCollectionsWithJSON(
+ // jsonString: string,
+ // destTeamID: string,
+ // destCollectionID: string | null,
+ // ): Promise<void> {
+ // let collectionsList: FBCollectionFolder[];
+
+ // try {
+ // collectionsList = JSON.parse(jsonString);
+
+ // if (!Array.isArray(collectionsList))
+ // throw new Error(TEAM_COLL_INVALID_JSON);
+ // } catch (e) {
+ // throw new Error(TEAM_COLL_INVALID_JSON);
+ // }
+ // const childrenCollection = await this.prisma.teamCollection.findMany({
+ // where: {
+ // teamID: destTeamID,
+ // parentID: destCollectionID,
+ // },
+ // });
+
+ // await Promise.all(
+ // childrenCollection.map(async (coll) => {
+ // await this.deleteCollection(coll.id);
+ // }),
+ // );
+
+ // const queryList = collectionsList.map((x) =>
+ // this.generatePrismaQueryObjForFBCollFolder(x, destTeamID),
+ // );
+
+ // let requests: TeamCollection[];
+
+ // if (destCollectionID) {
+ // requests = await this.prisma.$transaction(
+ // queryList.map((x) =>
+ // this.prisma.teamCollection.create({
+ // data: {
+ // ...x,
+ // parent: {
+ // connect: {
+ // id: destCollectionID,
+ // },
+ // },
+ // },
+ // }),
+ // ),
+ // );
+ // } else {
+ // requests = await this.prisma.$transaction(
+ // queryList.map((x) =>
+ // this.prisma.teamCollection.create({
+ // data: {
+ // ...x,
+ // },
+ // }),
+ // ),
+ // );
+ // }
+
+ // requests.forEach((x) =>
+ // this.pubsub.publish(`team_coll/${destTeamID}/coll_added`, x),
+ // );
+ // }
+
+ async getTeamOfCollection(collectionID: string): Promise<Team> {
+ const { team } =
+ (await this.prisma.teamCollection.findUnique({
+ where: {
+ id: collectionID,
+ },
+ include: {
+ team: true,
+ },
+ })) ?? throwErr(TEAM_INVALID_COLL_ID);
+
+ return team;
+ }
+
+ async getParentOfCollection(
+ collectionID: string,
+ ): Promise<TeamCollection | null> {
+ const { parent } =
+ (await this.prisma.teamCollection.findUnique({
+ where: {
+ id: collectionID,
+ },
+ include: {
+ parent: true,
+ },
+ })) ?? throwErr(TEAM_INVALID_COLL_ID);
+
+ return parent;
+ }
+
+ getChildrenOfCollection(
+ collectionID: string,
+ cursor: string | null,
+ ): Promise<TeamCollection[]> {
+ if (!cursor) {
+ return this.prisma.teamCollection.findMany({
+ take: 10,
+ where: {
+ parent: {
+ id: collectionID,
+ },
+ },
+ });
+ } else {
+ return this.prisma.teamCollection.findMany({
+ take: 10,
+ skip: 1,
+ cursor: {
+ id: cursor,
+ },
+ where: {
+ parent: {
+ id: collectionID,
+ },
+ },
+ });
+ }
+ }
+
+ async getTeamRootCollections(
+ teamID: string,
+ cursor: string | null,
+ ): Promise<TeamCollection[]> {
+ if (!cursor) {
+ return await this.prisma.teamCollection.findMany({
+ take: 10,
+ where: {
+ teamID,
+ parentID: null,
+ },
+ });
+ } else {
+ return this.prisma.teamCollection.findMany({
+ take: 10,
+ skip: 1,
+ cursor: {
+ id: cursor,
+ },
+ where: {
+ teamID,
+ parentID: null,
+ },
+ });
+ }
+ }
+
+ getTeamCollections(
+ teamID: string,
+ cursor: string | null,
+ ): Promise<TeamCollection[]> {
+ if (!cursor) {
+ return this.prisma.teamCollection.findMany({
+ take: 10,
+ where: {
+ teamID,
+ },
+ });
+ } else {
+ return this.prisma.teamCollection.findMany({
+ take: 10,
+ skip: 1,
+ cursor: {
+ id: cursor,
+ },
+ where: {
+ teamID,
+ },
+ });
+ }
+ }
+
+ getCollection(collectionID: string): Promise<TeamCollection | null> {
+ return this.prisma.teamCollection.findUnique({
+ where: {
+ id: collectionID,
+ },
+ });
+ }
+
+ getCollectionTO(collectionID: string): TO.TaskOption<TeamCollection> {
+ return pipe(
+ TO.fromTask(() => this.getCollection(collectionID)),
+ TO.chain(TO.fromNullable),
+ );
+ }
+
+ async createCollection(
+ teamID: string,
+ title: string,
+ parentID: string | null,
+ ): Promise<TeamCollection> {
+ if (title.length < 3) {
+ throw new Error(TEAM_COLL_SHORT_TITLE);
+ }
+
+ let result: TeamCollection;
+
+ if (!parentID) {
+ result = await this.prisma.teamCollection.create({
+ data: {
+ title: title,
+ team: {
+ connect: {
+ id: teamID,
+ },
+ },
+ },
+ });
+ } else {
+ result = await this.prisma.teamCollection.create({
+ data: {
+ title: title,
+ team: {
+ connect: {
+ id: teamID,
+ },
+ },
+ parent: {
+ connect: {
+ id: parentID,
+ },
+ },
+ },
+ });
+ }
+
+ this.pubsub.publish(`team_coll/${teamID}/coll_added`, result);
+
+ return result;
+ }
+
+ async renameCollection(
+ collectionID: string,
+ newTitle: string,
+ ): Promise<TeamCollection> {
+ if (newTitle.length < 3) {
+ throw new Error(TEAM_COLL_SHORT_TITLE);
+ }
+
+ const res = await this.prisma.teamCollection.update({
+ where: {
+ id: collectionID,
+ },
+ data: {
+ title: newTitle,
+ },
+ });
+
+ this.pubsub.publish(`team_coll/${res.teamID}/coll_updated`, res);
+
+ return res;
+ }
+
+ async deleteCollection(collectionID: string): Promise<void> {
+ const coll =
+ (await this.getCollection(collectionID)) ??
+ throwErr(TEAM_INVALID_COLL_ID);
+
+ const childrenCollection = await this.prisma.teamCollection.findMany({
+ where: {
+ parentID: coll.id,
+ },
+ });
+
+ await Promise.all(
+ childrenCollection.map((coll) => this.deleteCollection(coll.id)),
+ );
+
+ await this.prisma.teamRequest.deleteMany({
+ where: {
+ collectionID: coll.id,
+ },
+ });
+
+ await this.prisma.teamCollection.delete({
+ where: {
+ id: collectionID,
+ },
+ });
+
+ this.pubsub.publish(`team_coll/${coll.teamID}/coll_removed`, coll);
+ }
+}