Compare commits
15 Commits
feat/colle
...
feat/subpa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a134e20cdf | ||
|
|
a501282f2b | ||
|
|
eb248fa0df | ||
|
|
f1e4ac7fc4 | ||
|
|
28059ddc60 | ||
|
|
64517a53af | ||
|
|
79a9285f93 | ||
|
|
aebcbac979 | ||
|
|
d19d96ba9c | ||
|
|
312940009e | ||
|
|
8703a0dcfd | ||
|
|
03e21e0b0c | ||
|
|
d6e4b6497f | ||
|
|
2f1fca2917 | ||
|
|
04092d8597 |
@@ -12,8 +12,8 @@ SESSION_SECRET='add some secret here'
|
||||
|
||||
# Hoppscotch App Domain Config
|
||||
REDIRECT_URL="http://localhost:3000"
|
||||
WHITELISTED_ORIGINS="http://localhost:3170,http://localhost:3000,http://localhost:3100"
|
||||
VITE_ALLOWED_AUTH_PROVIDERS=GOOGLE,GITHUB,MICROSOFT,EMAIL
|
||||
WHITELISTED_ORIGINS = "http://localhost:3170,http://localhost:3000,http://localhost:3100"
|
||||
VITE_ALLOWED_AUTH_PROVIDERS = GOOGLE,GITHUB,MICROSOFT,EMAIL
|
||||
|
||||
# Google Auth Config
|
||||
GOOGLE_CLIENT_ID="************************************************"
|
||||
|
||||
14
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"antfu.iconify",
|
||||
"vue.volar",
|
||||
"esbenp.prettier-vscode",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"editorconfig.editorconfig",
|
||||
"csstools.postcss",
|
||||
"folke.vscode-monorepo-workspace"
|
||||
],
|
||||
"unwantedRecommendations": [
|
||||
"octref.vetur"
|
||||
]
|
||||
}
|
||||
11
Caddyfile
Normal file
@@ -0,0 +1,11 @@
|
||||
:3500 {
|
||||
handle_path /admin* {
|
||||
reverse_proxy localhost:3100
|
||||
}
|
||||
|
||||
handle_path /backend* {
|
||||
reverse_proxy localhost:3170
|
||||
}
|
||||
|
||||
reverse_proxy localhost:3000 # Proxy other requests to your server running on port 3001
|
||||
}
|
||||
@@ -6,14 +6,10 @@
|
||||
|
||||
:3100 {
|
||||
try_files {path} /
|
||||
root * /site/sh-admin-multiport-setup
|
||||
root * /site/sh-admin
|
||||
file_server
|
||||
}
|
||||
|
||||
:3170 {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
|
||||
:80 {
|
||||
respond 404
|
||||
}
|
||||
|
||||
@@ -6,10 +6,6 @@
|
||||
respond 404
|
||||
}
|
||||
|
||||
:3170 {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
|
||||
:80 {
|
||||
# Serve the `selfhost-web` SPA by default
|
||||
root * /site/selfhost-web
|
||||
|
||||
@@ -78,7 +78,7 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "3100:3100"
|
||||
- "3170:3170"
|
||||
- "3170:8080"
|
||||
- "3080:80"
|
||||
|
||||
# The preset DB service, you can delete/comment the below lines if
|
||||
|
||||
0
individual-containers-subpath-access.Caddyfile
Normal file
@@ -17,7 +17,7 @@
|
||||
"types": "dist/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.9.0",
|
||||
"@codemirror/language": "^6.9.2",
|
||||
"@lezer/highlight": "1.1.4",
|
||||
"@lezer/lr": "^1.3.13"
|
||||
},
|
||||
|
||||
3
packages/hoppscotch-backend/Caddyfile
Normal file
@@ -0,0 +1,3 @@
|
||||
:3170 {
|
||||
reverse_proxy localhost:80
|
||||
}
|
||||
3
packages/hoppscotch-backend/backend-multiport.Caddyfile
Normal file
@@ -0,0 +1,3 @@
|
||||
:80 :3170 {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
7
packages/hoppscotch-backend/backend-subpath.Caddyfile
Normal file
@@ -0,0 +1,7 @@
|
||||
:80 :3170 {
|
||||
handle_path /backend* {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
:80 :3170 {
|
||||
reverse_proxy localhost:8080
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hoppscotch-backend",
|
||||
"version": "2023.8.4-1",
|
||||
"version": "2023.8.3",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "TeamCollection" ADD COLUMN "data" JSONB;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "UserCollection" ADD COLUMN "data" JSONB;
|
||||
@@ -43,7 +43,6 @@ model TeamInvitation {
|
||||
model TeamCollection {
|
||||
id String @id @default(cuid())
|
||||
parentID String?
|
||||
data Json?
|
||||
parent TeamCollection? @relation("TeamCollectionChildParent", fields: [parentID], references: [id])
|
||||
children TeamCollection[] @relation("TeamCollectionChildParent")
|
||||
requests TeamRequest[]
|
||||
@@ -75,8 +74,7 @@ model Shortcode {
|
||||
creatorUid String?
|
||||
User User? @relation(fields: [creatorUid], references: [uid])
|
||||
createdOn DateTime @default(now())
|
||||
updatedOn DateTime @default(now()) @updatedAt
|
||||
|
||||
updatedOn DateTime @updatedAt @default(now())
|
||||
@@unique(fields: [id, creatorUid], name: "creator_uid_shortcode_unique")
|
||||
}
|
||||
|
||||
@@ -197,7 +195,6 @@ model UserCollection {
|
||||
userUid String
|
||||
user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)
|
||||
title String
|
||||
data Json?
|
||||
orderIndex Int
|
||||
type ReqType
|
||||
createdOn DateTime @default(now()) @db.Timestamp(3)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/local/bin/node
|
||||
// @ts-check
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import process from 'process';
|
||||
|
||||
function runChildProcessWithPrefix(command, args, prefix) {
|
||||
@@ -26,16 +27,20 @@ function runChildProcessWithPrefix(command, args, prefix) {
|
||||
});
|
||||
|
||||
childProcess.on('error', (stuff) => {
|
||||
console.error('error');
|
||||
console.error(stuff);
|
||||
console.log('error');
|
||||
console.log(stuff);
|
||||
});
|
||||
|
||||
return childProcess;
|
||||
}
|
||||
|
||||
const caddyFileName =
|
||||
process.env.ENABLE_SUBPATH_BASED_ACCESS === 'true'
|
||||
? 'backend-subpath.Caddyfile'
|
||||
: 'backend-multiport.Caddyfile';
|
||||
const caddyProcess = runChildProcessWithPrefix(
|
||||
'caddy',
|
||||
['run', '--config', '/etc/caddy/backend.Caddyfile', '--adapter', 'caddyfile'],
|
||||
['run', '--config', `/etc/caddy/${caddyFileName}`, '--adapter', 'caddyfile'],
|
||||
'App/Admin Dashboard Caddy',
|
||||
);
|
||||
const backendProcess = runChildProcessWithPrefix(
|
||||
|
||||
@@ -11,7 +11,6 @@ import { TeamEnvironmentsModule } from '../team-environments/team-environments.m
|
||||
import { TeamCollectionModule } from '../team-collection/team-collection.module';
|
||||
import { TeamRequestModule } from '../team-request/team-request.module';
|
||||
import { InfraResolver } from './infra.resolver';
|
||||
import { ShortcodeModule } from 'src/shortcode/shortcode.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -24,7 +23,6 @@ import { ShortcodeModule } from 'src/shortcode/shortcode.module';
|
||||
TeamEnvironmentsModule,
|
||||
TeamCollectionModule,
|
||||
TeamRequestModule,
|
||||
ShortcodeModule,
|
||||
],
|
||||
providers: [InfraResolver, AdminResolver, AdminService],
|
||||
exports: [AdminService],
|
||||
|
||||
@@ -443,23 +443,6 @@ export class AdminResolver {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean, {
|
||||
description: 'Revoke Shortcode by ID',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard, GqlAdminGuard)
|
||||
async revokeShortcodeByAdmin(
|
||||
@Args({
|
||||
name: 'code',
|
||||
description: 'The shortcode to delete',
|
||||
type: () => ID,
|
||||
})
|
||||
code: string,
|
||||
): Promise<boolean> {
|
||||
const res = await this.adminService.deleteShortcode(code);
|
||||
if (E.isLeft(res)) throwErr(res.left);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Subscriptions */
|
||||
|
||||
@Subscription(() => InvitedUser, {
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
INVALID_EMAIL,
|
||||
USER_ALREADY_INVITED,
|
||||
} from '../errors';
|
||||
import { ShortcodeService } from 'src/shortcode/shortcode.service';
|
||||
|
||||
const mockPrisma = mockDeep<PrismaService>();
|
||||
const mockPubSub = mockDeep<PubSubService>();
|
||||
@@ -26,7 +25,6 @@ const mockTeamRequestService = mockDeep<TeamRequestService>();
|
||||
const mockTeamInvitationService = mockDeep<TeamInvitationService>();
|
||||
const mockTeamCollectionService = mockDeep<TeamCollectionService>();
|
||||
const mockMailerService = mockDeep<MailerService>();
|
||||
const mockShortcodeService = mockDeep<ShortcodeService>();
|
||||
|
||||
const adminService = new AdminService(
|
||||
mockUserService,
|
||||
@@ -38,7 +36,6 @@ const adminService = new AdminService(
|
||||
mockPubSub as any,
|
||||
mockPrisma as any,
|
||||
mockMailerService,
|
||||
mockShortcodeService,
|
||||
);
|
||||
|
||||
const invitedUsers: InvitedUsers[] = [
|
||||
|
||||
@@ -24,7 +24,6 @@ import { TeamRequestService } from '../team-request/team-request.service';
|
||||
import { TeamEnvironmentsService } from '../team-environments/team-environments.service';
|
||||
import { TeamInvitationService } from '../team-invitation/team-invitation.service';
|
||||
import { TeamMemberRole } from '../team/team.model';
|
||||
import { ShortcodeService } from 'src/shortcode/shortcode.service';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
@@ -38,7 +37,6 @@ export class AdminService {
|
||||
private readonly pubsub: PubSubService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly mailerService: MailerService,
|
||||
private readonly shortcodeService: ShortcodeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -434,35 +432,4 @@ export class AdminService {
|
||||
|
||||
return E.right(teamInvite.right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all created ShortCodes
|
||||
*
|
||||
* @param args Pagination arguments
|
||||
* @param userEmail User email
|
||||
* @returns ShortcodeWithUserEmail
|
||||
*/
|
||||
async fetchAllShortcodes(
|
||||
cursorID: string,
|
||||
take: number,
|
||||
userEmail: string = null,
|
||||
) {
|
||||
return this.shortcodeService.fetchAllShortcodes(
|
||||
{ cursor: cursorID, take },
|
||||
userEmail,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a Shortcode
|
||||
*
|
||||
* @param shortcodeID ID of Shortcode being deleted
|
||||
* @returns Boolean on successful deletion
|
||||
*/
|
||||
async deleteShortcode(shortcodeID: string) {
|
||||
const result = await this.shortcodeService.deleteShortcode(shortcodeID);
|
||||
|
||||
if (E.isLeft(result)) return E.left(result.left);
|
||||
return E.right(result.right);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import { InvitedUser } from './invited-user.model';
|
||||
import { Team } from 'src/team/team.model';
|
||||
import { TeamInvitation } from 'src/team-invitation/team-invitation.model';
|
||||
import { GqlAdmin } from './decorators/gql-admin.decorator';
|
||||
import { ShortcodeWithUserEmail } from 'src/shortcode/shortcode.model';
|
||||
|
||||
@UseGuards(GqlThrottlerGuard)
|
||||
@Resolver(() => Infra)
|
||||
@@ -203,23 +202,4 @@ export class InfraResolver {
|
||||
async teamRequestsCount() {
|
||||
return this.adminService.getTeamRequestsCount();
|
||||
}
|
||||
|
||||
@ResolveField(() => [ShortcodeWithUserEmail], {
|
||||
description: 'Returns a list of all the shortcodes in the infra',
|
||||
})
|
||||
async allShortcodes(
|
||||
@Args() args: PaginationArgs,
|
||||
@Args({
|
||||
name: 'userEmail',
|
||||
nullable: true,
|
||||
description: 'Users email to filter shortcodes by',
|
||||
})
|
||||
userEmail: string,
|
||||
) {
|
||||
return await this.adminService.fetchAllShortcodes(
|
||||
args.cursor,
|
||||
args.take,
|
||||
userEmail,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,13 +254,6 @@ export const TEAM_COLL_INVALID_JSON = 'team_coll/invalid_json';
|
||||
*/
|
||||
export const TEAM_NOT_OWNER = 'team_coll/team_not_owner' as const;
|
||||
|
||||
/**
|
||||
* The Team Collection data is not valid
|
||||
* (TeamCollectionService)
|
||||
*/
|
||||
export const TEAM_COLL_DATA_INVALID =
|
||||
'team_coll/team_coll_data_invalid' as const;
|
||||
|
||||
/**
|
||||
* Tried to perform an action on a request that doesn't accept their member role level
|
||||
* (GqlRequestTeamMemberGuard)
|
||||
@@ -592,13 +585,6 @@ export const USER_COLL_REORDERING_FAILED =
|
||||
export const USER_COLL_SAME_NEXT_COLL =
|
||||
'user_coll/user_collection_and_next_user_collection_are_same' as const;
|
||||
|
||||
/**
|
||||
* The User Collection data is not valid
|
||||
* (UserCollectionService)
|
||||
*/
|
||||
export const USER_COLL_DATA_INVALID =
|
||||
'user_coll/user_coll_data_invalid' as const;
|
||||
|
||||
/**
|
||||
* The User Collection does not belong to the logged-in user
|
||||
* (UserCollectionService)
|
||||
|
||||
@@ -21,8 +21,8 @@ import {
|
||||
} from 'src/team-request/team-request.model';
|
||||
import { TeamInvitation } from 'src/team-invitation/team-invitation.model';
|
||||
import { InvitedUser } from '../admin/invited-user.model';
|
||||
import { UserCollection } from '@prisma/client';
|
||||
import {
|
||||
UserCollection,
|
||||
UserCollectionRemovedData,
|
||||
UserCollectionReorderData,
|
||||
} from 'src/user-collection/user-collections.model';
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Field, ID, ObjectType } from '@nestjs/graphql';
|
||||
import { User } from 'src/user/user.model';
|
||||
|
||||
@ObjectType()
|
||||
export class Shortcode {
|
||||
@@ -24,46 +23,3 @@ export class Shortcode {
|
||||
})
|
||||
createdOn: Date;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
export class ShortcodeCreator {
|
||||
@Field({
|
||||
description: 'Uid of user who created the shortcode',
|
||||
})
|
||||
uid: string;
|
||||
|
||||
@Field({
|
||||
description: 'Email of user who created the shortcode',
|
||||
})
|
||||
email: string;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
export class ShortcodeWithUserEmail {
|
||||
@Field(() => ID, {
|
||||
description: 'The 12 digit alphanumeric code',
|
||||
})
|
||||
id: string;
|
||||
|
||||
@Field({
|
||||
description: 'JSON string representing the request data',
|
||||
})
|
||||
request: string;
|
||||
|
||||
@Field({
|
||||
description: 'JSON string representing the properties for an embed',
|
||||
nullable: true,
|
||||
})
|
||||
properties: string;
|
||||
|
||||
@Field({
|
||||
description: 'Timestamp of when the Shortcode was created',
|
||||
})
|
||||
createdOn: Date;
|
||||
|
||||
@Field({
|
||||
description: 'Details of user who created the shortcode',
|
||||
nullable: true,
|
||||
})
|
||||
creator: ShortcodeCreator;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from '@nestjs/graphql';
|
||||
import * as E from 'fp-ts/Either';
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { Shortcode, ShortcodeWithUserEmail } from './shortcode.model';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { ShortcodeService } from './shortcode.service';
|
||||
import { throwErr } from 'src/utils';
|
||||
import { GqlUser } from 'src/decorators/gql-user.decorator';
|
||||
@@ -19,7 +19,6 @@ import { AuthUser } from '../types/AuthUser';
|
||||
import { PaginationArgs } from 'src/types/input-types.args';
|
||||
import { GqlThrottlerGuard } from 'src/guards/gql-throttler.guard';
|
||||
import { SkipThrottle } from '@nestjs/throttler';
|
||||
import { GqlAdminGuard } from 'src/admin/guards/gql-admin.guard';
|
||||
|
||||
@UseGuards(GqlThrottlerGuard)
|
||||
@Resolver(() => Shortcode)
|
||||
@@ -122,7 +121,7 @@ export class ShortcodeResolver {
|
||||
@Args({
|
||||
name: 'code',
|
||||
type: () => ID,
|
||||
description: 'The shortcode to remove',
|
||||
description: 'The shortcode to resolve',
|
||||
})
|
||||
code: string,
|
||||
) {
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { mockDeep, mockReset } from 'jest-mock-extended';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
INVALID_EMAIL,
|
||||
SHORTCODE_INVALID_PROPERTIES_JSON,
|
||||
SHORTCODE_INVALID_REQUEST_JSON,
|
||||
SHORTCODE_NOT_FOUND,
|
||||
SHORTCODE_PROPERTIES_NOT_FOUND,
|
||||
} from 'src/errors';
|
||||
import { Shortcode, ShortcodeWithUserEmail } from './shortcode.model';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { ShortcodeService } from './shortcode.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
import { AuthUser } from 'src/types/AuthUser';
|
||||
@@ -98,35 +97,6 @@ const shortcodes = [
|
||||
},
|
||||
];
|
||||
|
||||
const shortcodesWithUserEmail = [
|
||||
{
|
||||
id: 'blablabla',
|
||||
request: {
|
||||
hello: 'there',
|
||||
},
|
||||
embedProperties: {
|
||||
foo: 'bar',
|
||||
},
|
||||
creatorUid: user.uid,
|
||||
createdOn: new Date(),
|
||||
updatedOn: createdOn,
|
||||
User: user,
|
||||
},
|
||||
{
|
||||
id: 'blablabla1',
|
||||
request: {
|
||||
hello: 'there',
|
||||
},
|
||||
embedProperties: {
|
||||
foo: 'bar',
|
||||
},
|
||||
creatorUid: user.uid,
|
||||
createdOn: new Date(),
|
||||
updatedOn: createdOn,
|
||||
User: user,
|
||||
},
|
||||
];
|
||||
|
||||
describe('ShortcodeService', () => {
|
||||
describe('getShortCode', () => {
|
||||
test('should return a valid Shortcode with valid Shortcode ID', async () => {
|
||||
@@ -471,99 +441,4 @@ describe('ShortcodeService', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteShortcode', () => {
|
||||
test('should return true on successful deletion of Shortcode with valid inputs', async () => {
|
||||
mockPrisma.shortcode.delete.mockResolvedValueOnce(mockEmbed);
|
||||
|
||||
const result = await shortcodeService.deleteShortcode(mockEmbed.id);
|
||||
expect(result).toEqualRight(true);
|
||||
});
|
||||
|
||||
test('should return SHORTCODE_NOT_FOUND error when Shortcode is invalid', async () => {
|
||||
mockPrisma.shortcode.delete.mockRejectedValue('RecordNotFound');
|
||||
|
||||
expect(shortcodeService.deleteShortcode('invalid')).resolves.toEqualLeft(
|
||||
SHORTCODE_NOT_FOUND,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchAllShortcodes', () => {
|
||||
test('should return list of Shortcodes with valid inputs and no cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValueOnce(
|
||||
shortcodesWithUserEmail,
|
||||
);
|
||||
|
||||
const result = await shortcodeService.fetchAllShortcodes(
|
||||
{
|
||||
cursor: null,
|
||||
take: 10,
|
||||
},
|
||||
user.email,
|
||||
);
|
||||
expect(result).toEqual(<ShortcodeWithUserEmail[]>[
|
||||
{
|
||||
id: shortcodes[0].id,
|
||||
request: JSON.stringify(shortcodes[0].request),
|
||||
properties: JSON.stringify(shortcodes[0].embedProperties),
|
||||
createdOn: shortcodes[0].createdOn,
|
||||
creator: {
|
||||
uid: user.uid,
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: shortcodes[1].id,
|
||||
request: JSON.stringify(shortcodes[1].request),
|
||||
properties: JSON.stringify(shortcodes[1].embedProperties),
|
||||
createdOn: shortcodes[1].createdOn,
|
||||
creator: {
|
||||
uid: user.uid,
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('should return list of Shortcode with valid inputs and cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValue([
|
||||
shortcodesWithUserEmail[1],
|
||||
]);
|
||||
|
||||
const result = await shortcodeService.fetchAllShortcodes(
|
||||
{
|
||||
cursor: 'blablabla',
|
||||
take: 10,
|
||||
},
|
||||
user.email,
|
||||
);
|
||||
expect(result).toEqual(<ShortcodeWithUserEmail[]>[
|
||||
{
|
||||
id: shortcodes[1].id,
|
||||
request: JSON.stringify(shortcodes[1].request),
|
||||
properties: JSON.stringify(shortcodes[1].embedProperties),
|
||||
createdOn: shortcodes[1].createdOn,
|
||||
creator: {
|
||||
uid: user.uid,
|
||||
email: user.email,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('should return an empty array for an invalid cursor', async () => {
|
||||
mockPrisma.shortcode.findMany.mockResolvedValue([]);
|
||||
|
||||
const result = await shortcodeService.fetchAllShortcodes(
|
||||
{
|
||||
cursor: 'invalidcursor',
|
||||
take: 10,
|
||||
},
|
||||
user.email,
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
SHORTCODE_PROPERTIES_NOT_FOUND,
|
||||
} from 'src/errors';
|
||||
import { UserDataHandler } from 'src/user/user.data.handler';
|
||||
import { Shortcode, ShortcodeWithUserEmail } from './shortcode.model';
|
||||
import { Shortcode } from './shortcode.model';
|
||||
import { Shortcode as DBShortCode } from '@prisma/client';
|
||||
import { PubSubService } from 'src/pubsub/pubsub.service';
|
||||
import { UserService } from 'src/user/user.service';
|
||||
@@ -180,7 +180,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a ShortCode created by User of uid
|
||||
* Delete a ShortCode
|
||||
*
|
||||
* @param shortcode ShortCode
|
||||
* @param uid User Uid
|
||||
@@ -223,26 +223,6 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
return deletedShortCodes.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a Shortcode
|
||||
*
|
||||
* @param shortcodeID ID of Shortcode being deleted
|
||||
* @returns Boolean on successful deletion
|
||||
*/
|
||||
async deleteShortcode(shortcodeID: string) {
|
||||
try {
|
||||
await this.prisma.shortcode.delete({
|
||||
where: {
|
||||
id: shortcodeID,
|
||||
},
|
||||
});
|
||||
|
||||
return E.right(true);
|
||||
} catch (error) {
|
||||
return E.left(SHORTCODE_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a created Shortcode
|
||||
* @param shortcodeID Shortcode ID
|
||||
@@ -283,57 +263,4 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {
|
||||
return E.left(SHORTCODE_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all created ShortCodes
|
||||
*
|
||||
* @param args Pagination arguments
|
||||
* @param userEmail User email
|
||||
* @returns ShortcodeWithUserEmail
|
||||
*/
|
||||
async fetchAllShortcodes(
|
||||
args: PaginationArgs,
|
||||
userEmail: string | null = null,
|
||||
) {
|
||||
const shortCodes = await this.prisma.shortcode.findMany({
|
||||
where: userEmail
|
||||
? {
|
||||
User: {
|
||||
email: userEmail,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
orderBy: {
|
||||
createdOn: 'desc',
|
||||
},
|
||||
skip: args.cursor ? 1 : 0,
|
||||
take: args.take,
|
||||
cursor: args.cursor ? { id: args.cursor } : undefined,
|
||||
include: {
|
||||
User: true,
|
||||
},
|
||||
});
|
||||
|
||||
const fetchedShortCodes: ShortcodeWithUserEmail[] = shortCodes.map(
|
||||
(code) => {
|
||||
return <ShortcodeWithUserEmail>{
|
||||
id: code.id,
|
||||
request: JSON.stringify(code.request),
|
||||
properties:
|
||||
code.embedProperties != null
|
||||
? JSON.stringify(code.embedProperties)
|
||||
: null,
|
||||
createdOn: code.createdOn,
|
||||
creator: code.User
|
||||
? {
|
||||
uid: code.User.uid,
|
||||
email: code.User.email,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return fetchedShortCodes;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,13 +14,6 @@ export class CreateRootTeamCollectionArgs {
|
||||
|
||||
@Field({ name: 'title', description: 'Title of the new collection' })
|
||||
title: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
|
||||
@ArgsType()
|
||||
@@ -33,13 +26,6 @@ export class CreateChildTeamCollectionArgs {
|
||||
|
||||
@Field({ name: 'childTitle', description: 'Title of the new collection' })
|
||||
childTitle: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
|
||||
@ArgsType()
|
||||
@@ -47,14 +33,12 @@ export class RenameTeamCollectionArgs {
|
||||
@Field(() => ID, {
|
||||
name: 'collectionID',
|
||||
description: 'ID of the collection',
|
||||
deprecationReason: 'Switch to updateTeamCollection mutation instead',
|
||||
})
|
||||
collectionID: string;
|
||||
|
||||
@Field({
|
||||
name: 'newTitle',
|
||||
description: 'The updated title of the collection',
|
||||
deprecationReason: 'Switch to updateTeamCollection mutation instead',
|
||||
})
|
||||
newTitle: string;
|
||||
}
|
||||
@@ -114,26 +98,3 @@ export class ReplaceTeamCollectionArgs {
|
||||
})
|
||||
parentCollectionID?: string;
|
||||
}
|
||||
|
||||
@ArgsType()
|
||||
export class UpdateTeamCollectionArgs {
|
||||
@Field(() => ID, {
|
||||
name: 'collectionID',
|
||||
description: 'ID of the collection',
|
||||
})
|
||||
collectionID: string;
|
||||
|
||||
@Field({
|
||||
name: 'newTitle',
|
||||
description: 'The updated title of the collection',
|
||||
nullable: true,
|
||||
})
|
||||
newTitle: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
|
||||
@@ -12,17 +12,12 @@ export class TeamCollection {
|
||||
})
|
||||
title: string;
|
||||
|
||||
@Field({
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
|
||||
@Field(() => ID, {
|
||||
description: 'ID of the collection',
|
||||
nullable: true,
|
||||
})
|
||||
parentID: string;
|
||||
teamID: string;
|
||||
}
|
||||
|
||||
@ObjectType()
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
MoveTeamCollectionArgs,
|
||||
RenameTeamCollectionArgs,
|
||||
ReplaceTeamCollectionArgs,
|
||||
UpdateTeamCollectionArgs,
|
||||
UpdateTeamCollectionOrderArgs,
|
||||
} from './input-type.args';
|
||||
import * as E from 'fp-ts/Either';
|
||||
@@ -142,14 +141,7 @@ export class TeamCollectionResolver {
|
||||
);
|
||||
|
||||
if (E.isLeft(teamCollections)) throwErr(teamCollections.left);
|
||||
return <TeamCollection>{
|
||||
id: teamCollections.right.id,
|
||||
title: teamCollections.right.title,
|
||||
parentID: teamCollections.right.parentID,
|
||||
data: !teamCollections.right.data
|
||||
? null
|
||||
: JSON.stringify(teamCollections.right.data),
|
||||
};
|
||||
return teamCollections.right;
|
||||
}
|
||||
|
||||
// Mutations
|
||||
@@ -163,7 +155,6 @@ export class TeamCollectionResolver {
|
||||
const teamCollection = await this.teamCollectionService.createCollection(
|
||||
args.teamID,
|
||||
args.title,
|
||||
args.data,
|
||||
null,
|
||||
);
|
||||
|
||||
@@ -239,7 +230,6 @@ export class TeamCollectionResolver {
|
||||
const teamCollection = await this.teamCollectionService.createCollection(
|
||||
team.right.id,
|
||||
args.childTitle,
|
||||
args.data,
|
||||
args.collectionID,
|
||||
);
|
||||
|
||||
@@ -249,7 +239,6 @@ export class TeamCollectionResolver {
|
||||
|
||||
@Mutation(() => TeamCollection, {
|
||||
description: 'Rename a collection',
|
||||
deprecationReason: 'Switch to updateTeamCollection mutation instead',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
|
||||
@RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
|
||||
@@ -314,23 +303,6 @@ export class TeamCollectionResolver {
|
||||
return request.right;
|
||||
}
|
||||
|
||||
@Mutation(() => TeamCollection, {
|
||||
description: 'Update Team Collection details',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard, GqlCollectionTeamMemberGuard)
|
||||
@RequiresTeamRole(TeamMemberRole.OWNER, TeamMemberRole.EDITOR)
|
||||
async updateTeamCollection(@Args() args: UpdateTeamCollectionArgs) {
|
||||
const updatedTeamCollection =
|
||||
await this.teamCollectionService.updateTeamCollection(
|
||||
args.collectionID,
|
||||
args.data,
|
||||
args.newTitle,
|
||||
);
|
||||
|
||||
if (E.isLeft(updatedTeamCollection)) throwErr(updatedTeamCollection.left);
|
||||
return updatedTeamCollection.right;
|
||||
}
|
||||
|
||||
// Subscriptions
|
||||
|
||||
@Subscription(() => TeamCollection, {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Team, TeamCollection as DBTeamCollection } from '@prisma/client';
|
||||
import { mockDeep, mockReset } from 'jest-mock-extended';
|
||||
import {
|
||||
TEAM_COLL_DATA_INVALID,
|
||||
TEAM_COLL_DEST_SAME,
|
||||
TEAM_COLL_INVALID_JSON,
|
||||
TEAM_COLL_IS_PARENT_COLL,
|
||||
@@ -18,7 +17,6 @@ import { PrismaService } from 'src/prisma/prisma.service';
|
||||
import { PubSubService } from 'src/pubsub/pubsub.service';
|
||||
import { AuthUser } from 'src/types/AuthUser';
|
||||
import { TeamCollectionService } from './team-collection.service';
|
||||
import { TeamCollection } from './team-collection.model';
|
||||
|
||||
const mockPrisma = mockDeep<PrismaService>();
|
||||
const mockPubSub = mockDeep<PubSubService>();
|
||||
@@ -53,60 +51,35 @@ const rootTeamCollection: DBTeamCollection = {
|
||||
id: '123',
|
||||
orderIndex: 1,
|
||||
parentID: null,
|
||||
data: {},
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
};
|
||||
|
||||
const rootTeamCollectionsCasted: TeamCollection = {
|
||||
id: rootTeamCollection.id,
|
||||
title: rootTeamCollection.title,
|
||||
parentID: rootTeamCollection.parentID,
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
};
|
||||
|
||||
const rootTeamCollection_2: DBTeamCollection = {
|
||||
id: 'erv',
|
||||
orderIndex: 2,
|
||||
parentID: null,
|
||||
data: {},
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
};
|
||||
|
||||
const rootTeamCollection_2Casted: TeamCollection = {
|
||||
id: 'erv',
|
||||
parentID: null,
|
||||
data: JSON.stringify(rootTeamCollection_2.data),
|
||||
title: 'Root Collection 1',
|
||||
};
|
||||
|
||||
const childTeamCollection: DBTeamCollection = {
|
||||
id: 'rfe',
|
||||
orderIndex: 1,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
title: 'Child Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
};
|
||||
|
||||
const childTeamCollectionCasted: TeamCollection = {
|
||||
id: 'rfe',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify(childTeamCollection.data),
|
||||
title: 'Child Collection 1',
|
||||
};
|
||||
|
||||
const childTeamCollection_2: DBTeamCollection = {
|
||||
id: 'bgdz',
|
||||
orderIndex: 1,
|
||||
data: {},
|
||||
parentID: rootTeamCollection_2.id,
|
||||
title: 'Child Collection 1',
|
||||
teamID: team.id,
|
||||
@@ -114,20 +87,11 @@ const childTeamCollection_2: DBTeamCollection = {
|
||||
updatedOn: currentTime,
|
||||
};
|
||||
|
||||
const childTeamCollection_2Casted: TeamCollection = {
|
||||
id: 'bgdz',
|
||||
data: JSON.stringify(childTeamCollection_2.data),
|
||||
parentID: rootTeamCollection_2.id,
|
||||
title: 'Child Collection 1',
|
||||
};
|
||||
|
||||
const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
{
|
||||
id: 'fdv',
|
||||
orderIndex: 1,
|
||||
parentID: null,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -138,8 +102,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 2,
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -149,8 +111,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 3,
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -159,8 +119,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
id: 'bre3',
|
||||
orderIndex: 4,
|
||||
parentID: null,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -171,8 +129,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 5,
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -183,8 +139,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
data: {},
|
||||
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
},
|
||||
@@ -194,8 +148,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
data: {},
|
||||
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
},
|
||||
@@ -204,7 +156,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 8,
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -214,7 +165,6 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 9,
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -225,83 +175,17 @@ const rootTeamCollectionList: DBTeamCollection[] = [
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
data: {},
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
},
|
||||
];
|
||||
|
||||
const rootTeamCollectionListCasted: TeamCollection[] = [
|
||||
{
|
||||
id: 'fdv',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: 'fbbg',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: 'fgbfg',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: 'bre3',
|
||||
parentID: null,
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: 'hghgf',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: '123',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: '54tyh',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: '234re',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: '34rtg',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
{
|
||||
id: '45tgh',
|
||||
parentID: null,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify(rootTeamCollection.data),
|
||||
},
|
||||
];
|
||||
|
||||
const childTeamCollectionList: DBTeamCollection[] = [
|
||||
{
|
||||
id: '123',
|
||||
orderIndex: 1,
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -311,8 +195,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 2,
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -322,8 +204,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
orderIndex: 3,
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: {},
|
||||
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
updatedOn: currentTime,
|
||||
@@ -332,8 +212,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '567',
|
||||
orderIndex: 4,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -343,8 +221,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '123',
|
||||
orderIndex: 5,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -354,8 +230,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '678',
|
||||
orderIndex: 6,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -365,8 +239,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '789',
|
||||
orderIndex: 7,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -376,8 +248,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '890',
|
||||
orderIndex: 8,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -387,7 +257,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '012',
|
||||
orderIndex: 9,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -397,8 +266,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
id: '0bhu',
|
||||
orderIndex: 10,
|
||||
parentID: rootTeamCollection.id,
|
||||
data: {},
|
||||
|
||||
title: 'Root Collection 1',
|
||||
teamID: team.id,
|
||||
createdOn: currentTime,
|
||||
@@ -406,75 +273,6 @@ const childTeamCollectionList: DBTeamCollection[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const childTeamCollectionListCasted: TeamCollection[] = [
|
||||
{
|
||||
id: '123',
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify({}),
|
||||
},
|
||||
{
|
||||
id: '345',
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify({}),
|
||||
},
|
||||
{
|
||||
id: '456',
|
||||
parentID: rootTeamCollection.id,
|
||||
title: 'Root Collection 1',
|
||||
data: JSON.stringify({}),
|
||||
},
|
||||
{
|
||||
id: '567',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '123',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '678',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '789',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '890',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '012',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
{
|
||||
id: '0bhu',
|
||||
parentID: rootTeamCollection.id,
|
||||
data: JSON.stringify({}),
|
||||
|
||||
title: 'Root Collection 1',
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mockReset(mockPrisma);
|
||||
mockPubSub.publish.mockClear();
|
||||
@@ -513,7 +311,7 @@ describe('getParentOfCollection', () => {
|
||||
const result = await teamCollectionService.getParentOfCollection(
|
||||
childTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqual(rootTeamCollectionsCasted);
|
||||
expect(result).toEqual(rootTeamCollection);
|
||||
});
|
||||
|
||||
test('should return null successfully for a root collection with valid collectionID', async () => {
|
||||
@@ -549,7 +347,7 @@ describe('getChildrenOfCollection', () => {
|
||||
null,
|
||||
10,
|
||||
);
|
||||
expect(result).toEqual(childTeamCollectionListCasted);
|
||||
expect(result).toEqual(childTeamCollectionList);
|
||||
});
|
||||
|
||||
test('should return a list of 3 child collections successfully with cursor being equal to the 7th item in the list', async () => {
|
||||
@@ -565,9 +363,9 @@ describe('getChildrenOfCollection', () => {
|
||||
10,
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{ ...childTeamCollectionListCasted[7] },
|
||||
{ ...childTeamCollectionListCasted[8] },
|
||||
{ ...childTeamCollectionListCasted[9] },
|
||||
{ ...childTeamCollectionList[7] },
|
||||
{ ...childTeamCollectionList[8] },
|
||||
{ ...childTeamCollectionList[9] },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -594,7 +392,7 @@ describe('getTeamRootCollections', () => {
|
||||
null,
|
||||
10,
|
||||
);
|
||||
expect(result).toEqual(rootTeamCollectionListCasted);
|
||||
expect(result).toEqual(rootTeamCollectionList);
|
||||
});
|
||||
|
||||
test('should return a list of 3 root collections successfully with cursor being equal to the 7th item in the list', async () => {
|
||||
@@ -610,9 +408,9 @@ describe('getTeamRootCollections', () => {
|
||||
10,
|
||||
);
|
||||
expect(result).toEqual([
|
||||
{ ...rootTeamCollectionListCasted[7] },
|
||||
{ ...rootTeamCollectionListCasted[8] },
|
||||
{ ...rootTeamCollectionListCasted[9] },
|
||||
{ ...rootTeamCollectionList[7] },
|
||||
{ ...rootTeamCollectionList[8] },
|
||||
{ ...rootTeamCollectionList[9] },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -666,7 +464,6 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
rootTeamCollection.teamID,
|
||||
'ab',
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_COLL_SHORT_TITLE);
|
||||
@@ -681,27 +478,11 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
rootTeamCollection.teamID,
|
||||
'abcd',
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_NOT_OWNER);
|
||||
});
|
||||
|
||||
test('should throw TEAM_COLL_DATA_INVALID when parent TeamCollection does not belong to the team', async () => {
|
||||
// isOwnerCheck
|
||||
mockPrisma.teamCollection.findFirstOrThrow.mockResolvedValueOnce(
|
||||
rootTeamCollection,
|
||||
);
|
||||
|
||||
const result = await teamCollectionService.createCollection(
|
||||
rootTeamCollection.teamID,
|
||||
'abcd',
|
||||
'{',
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_COLL_DATA_INVALID);
|
||||
});
|
||||
|
||||
test('should successfully create a new root TeamCollection with valid inputs', async () => {
|
||||
// isOwnerCheck
|
||||
mockPrisma.teamCollection.findFirstOrThrow.mockResolvedValueOnce(
|
||||
@@ -715,10 +496,9 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
rootTeamCollection.teamID,
|
||||
'abcdefg',
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqualRight(rootTeamCollectionsCasted);
|
||||
expect(result).toEqualRight(rootTeamCollection);
|
||||
});
|
||||
|
||||
test('should successfully create a new child TeamCollection with valid inputs', async () => {
|
||||
@@ -734,10 +514,9 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
childTeamCollection.teamID,
|
||||
childTeamCollection.title,
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(result).toEqualRight(childTeamCollectionCasted);
|
||||
expect(result).toEqualRight(childTeamCollection);
|
||||
});
|
||||
|
||||
test('should send pubsub message to "team_coll/<teamID>/coll_added" if child TeamCollection is created successfully', async () => {
|
||||
@@ -753,13 +532,11 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
childTeamCollection.teamID,
|
||||
childTeamCollection.title,
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollection.teamID}/coll_added`,
|
||||
childTeamCollectionCasted,
|
||||
childTeamCollection,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -776,13 +553,11 @@ describe('createCollection', () => {
|
||||
const result = await teamCollectionService.createCollection(
|
||||
rootTeamCollection.teamID,
|
||||
'abcdefg',
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
|
||||
rootTeamCollection.id,
|
||||
);
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${rootTeamCollection.teamID}/coll_added`,
|
||||
rootTeamCollectionsCasted,
|
||||
rootTeamCollection,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -812,7 +587,7 @@ describe('renameCollection', () => {
|
||||
'NewTitle',
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
...rootTeamCollectionsCasted,
|
||||
...rootTeamCollection,
|
||||
title: 'NewTitle',
|
||||
});
|
||||
});
|
||||
@@ -850,7 +625,7 @@ describe('renameCollection', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${rootTeamCollection.teamID}/coll_updated`,
|
||||
{
|
||||
...rootTeamCollectionsCasted,
|
||||
...rootTeamCollection,
|
||||
title: 'NewTitle',
|
||||
},
|
||||
);
|
||||
@@ -1057,8 +832,9 @@ describe('moveCollection', () => {
|
||||
null,
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
...childTeamCollectionCasted,
|
||||
...childTeamCollection,
|
||||
parentID: null,
|
||||
orderIndex: 2,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1114,8 +890,9 @@ describe('moveCollection', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollection.teamID}/coll_moved`,
|
||||
{
|
||||
...childTeamCollectionCasted,
|
||||
...childTeamCollection,
|
||||
parentID: null,
|
||||
orderIndex: 2,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1154,8 +931,9 @@ describe('moveCollection', () => {
|
||||
childTeamCollection_2.id,
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
...rootTeamCollectionsCasted,
|
||||
parentID: childTeamCollection_2Casted.id,
|
||||
...rootTeamCollection,
|
||||
parentID: childTeamCollection_2.id,
|
||||
orderIndex: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1195,8 +973,9 @@ describe('moveCollection', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollection_2.teamID}/coll_moved`,
|
||||
{
|
||||
...rootTeamCollectionsCasted,
|
||||
parentID: childTeamCollection_2Casted.id,
|
||||
...rootTeamCollection,
|
||||
parentID: childTeamCollection_2.id,
|
||||
orderIndex: 1,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1235,8 +1014,9 @@ describe('moveCollection', () => {
|
||||
childTeamCollection_2.id,
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
...childTeamCollectionCasted,
|
||||
parentID: childTeamCollection_2Casted.id,
|
||||
...childTeamCollection,
|
||||
parentID: childTeamCollection_2.id,
|
||||
orderIndex: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1276,8 +1056,9 @@ describe('moveCollection', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollection.teamID}/coll_moved`,
|
||||
{
|
||||
...childTeamCollectionCasted,
|
||||
parentID: childTeamCollection_2Casted.id,
|
||||
...childTeamCollection,
|
||||
parentID: childTeamCollection_2.id,
|
||||
orderIndex: 1,
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1373,7 +1154,7 @@ describe('updateCollectionOrder', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollectionList[4].teamID}/coll_order_updated`,
|
||||
{
|
||||
collection: rootTeamCollectionListCasted[4],
|
||||
collection: rootTeamCollectionList[4],
|
||||
nextCollection: null,
|
||||
},
|
||||
);
|
||||
@@ -1454,8 +1235,8 @@ describe('updateCollectionOrder', () => {
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${childTeamCollectionList[2].teamID}/coll_order_updated`,
|
||||
{
|
||||
collection: childTeamCollectionListCasted[4],
|
||||
nextCollection: childTeamCollectionListCasted[2],
|
||||
collection: childTeamCollectionList[4],
|
||||
nextCollection: childTeamCollectionList[2],
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1521,7 +1302,7 @@ describe('importCollectionsFromJSON', () => {
|
||||
);
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${rootTeamCollection.teamID}/coll_added`,
|
||||
rootTeamCollectionsCasted,
|
||||
rootTeamCollection,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1640,7 +1421,7 @@ describe('replaceCollectionsWithJSON', () => {
|
||||
);
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${rootTeamCollection.teamID}/coll_added`,
|
||||
rootTeamCollectionsCasted,
|
||||
rootTeamCollection,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1677,64 +1458,4 @@ describe('totalCollectionsInTeam', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateTeamCollection', () => {
|
||||
test('should throw TEAM_COLL_SHORT_TITLE if title is invalid', async () => {
|
||||
const result = await teamCollectionService.updateTeamCollection(
|
||||
rootTeamCollection.id,
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
'de',
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_COLL_SHORT_TITLE);
|
||||
});
|
||||
|
||||
test('should throw TEAM_COLL_DATA_INVALID is collection data is invalid', async () => {
|
||||
const result = await teamCollectionService.updateTeamCollection(
|
||||
rootTeamCollection.id,
|
||||
'{',
|
||||
rootTeamCollection.title,
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_COLL_DATA_INVALID);
|
||||
});
|
||||
|
||||
test('should throw TEAM_COLL_NOT_FOUND is collectionID is invalid', async () => {
|
||||
mockPrisma.teamCollection.update.mockRejectedValueOnce('RecordNotFound');
|
||||
|
||||
const result = await teamCollectionService.updateTeamCollection(
|
||||
'invalid_id',
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.title,
|
||||
);
|
||||
expect(result).toEqualLeft(TEAM_COLL_NOT_FOUND);
|
||||
});
|
||||
|
||||
test('should successfully update a collection', async () => {
|
||||
mockPrisma.teamCollection.update.mockResolvedValueOnce(rootTeamCollection);
|
||||
|
||||
const result = await teamCollectionService.updateTeamCollection(
|
||||
rootTeamCollection.id,
|
||||
JSON.stringify({ foo: 'bar' }),
|
||||
'new_title',
|
||||
);
|
||||
expect(result).toEqualRight({
|
||||
data: JSON.stringify({ foo: 'bar' }),
|
||||
title: 'new_title',
|
||||
...rootTeamCollectionsCasted,
|
||||
});
|
||||
});
|
||||
|
||||
test('should send pubsub message to "team_coll/<teamID>/coll_updated" if TeamCollection is updated successfully', async () => {
|
||||
mockPrisma.teamCollection.update.mockResolvedValueOnce(rootTeamCollection);
|
||||
|
||||
const result = await teamCollectionService.updateTeamCollection(
|
||||
rootTeamCollection.id,
|
||||
JSON.stringify(rootTeamCollection.data),
|
||||
rootTeamCollection.title,
|
||||
);
|
||||
expect(mockPubSub.publish).toHaveBeenCalledWith(
|
||||
`team_coll/${rootTeamCollection.teamID}/coll_updated`,
|
||||
rootTeamCollectionsCasted,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
//ToDo: write test cases for exportCollectionsToJSON
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
TEAM_COLL_IS_PARENT_COLL,
|
||||
TEAM_COL_SAME_NEXT_COLL,
|
||||
TEAM_COL_REORDERING_FAILED,
|
||||
TEAM_COLL_DATA_INVALID,
|
||||
} from '../errors';
|
||||
import { PubSubService } from '../pubsub/pubsub.service';
|
||||
import { isValidLength } from 'src/utils';
|
||||
@@ -70,7 +69,6 @@ export class TeamCollectionService {
|
||||
this.generatePrismaQueryObjForFBCollFolder(f, teamID, index + 1),
|
||||
),
|
||||
},
|
||||
data: folder.data ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,7 +118,6 @@ export class TeamCollectionService {
|
||||
name: collection.right.title,
|
||||
folders: childrenCollectionObjects,
|
||||
requests: requests.map((x) => x.request),
|
||||
data: JSON.stringify(collection.right.data),
|
||||
};
|
||||
|
||||
return E.right(result);
|
||||
@@ -201,11 +198,8 @@ export class TeamCollectionService {
|
||||
),
|
||||
);
|
||||
|
||||
teamCollections.forEach((collection) =>
|
||||
this.pubsub.publish(
|
||||
`team_coll/${destTeamID}/coll_added`,
|
||||
this.cast(collection),
|
||||
),
|
||||
teamCollections.forEach((x) =>
|
||||
this.pubsub.publish(`team_coll/${destTeamID}/coll_added`, x),
|
||||
);
|
||||
|
||||
return E.right(true);
|
||||
@@ -274,11 +268,8 @@ export class TeamCollectionService {
|
||||
),
|
||||
);
|
||||
|
||||
teamCollections.forEach((collections) =>
|
||||
this.pubsub.publish(
|
||||
`team_coll/${destTeamID}/coll_added`,
|
||||
this.cast(collections),
|
||||
),
|
||||
teamCollections.forEach((x) =>
|
||||
this.pubsub.publish(`team_coll/${destTeamID}/coll_added`, x),
|
||||
);
|
||||
|
||||
return E.right(true);
|
||||
@@ -286,17 +277,11 @@ export class TeamCollectionService {
|
||||
|
||||
/**
|
||||
* Typecast a database TeamCollection to a TeamCollection model
|
||||
*
|
||||
* @param teamCollection database TeamCollection
|
||||
* @returns TeamCollection model
|
||||
*/
|
||||
private cast(teamCollection: DBTeamCollection): TeamCollection {
|
||||
return <TeamCollection>{
|
||||
id: teamCollection.id,
|
||||
title: teamCollection.title,
|
||||
parentID: teamCollection.parentID,
|
||||
data: !teamCollection.data ? null : JSON.stringify(teamCollection.data),
|
||||
};
|
||||
return <TeamCollection>{ ...teamCollection };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -339,7 +324,7 @@ export class TeamCollectionService {
|
||||
});
|
||||
if (!teamCollection) return null;
|
||||
|
||||
return !teamCollection.parent ? null : this.cast(teamCollection.parent);
|
||||
return teamCollection.parent;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -350,12 +335,12 @@ export class TeamCollectionService {
|
||||
* @param take Number of items we want returned
|
||||
* @returns A list of child collections
|
||||
*/
|
||||
async getChildrenOfCollection(
|
||||
getChildrenOfCollection(
|
||||
collectionID: string,
|
||||
cursor: string | null,
|
||||
take: number,
|
||||
) {
|
||||
const res = await this.prisma.teamCollection.findMany({
|
||||
return this.prisma.teamCollection.findMany({
|
||||
where: {
|
||||
parentID: collectionID,
|
||||
},
|
||||
@@ -366,12 +351,6 @@ export class TeamCollectionService {
|
||||
skip: cursor ? 1 : 0,
|
||||
cursor: cursor ? { id: cursor } : undefined,
|
||||
});
|
||||
|
||||
const childCollections = res.map((teamCollection) =>
|
||||
this.cast(teamCollection),
|
||||
);
|
||||
|
||||
return childCollections;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -387,7 +366,7 @@ export class TeamCollectionService {
|
||||
cursor: string | null,
|
||||
take: number,
|
||||
) {
|
||||
const res = await this.prisma.teamCollection.findMany({
|
||||
return this.prisma.teamCollection.findMany({
|
||||
where: {
|
||||
teamID,
|
||||
parentID: null,
|
||||
@@ -399,12 +378,6 @@ export class TeamCollectionService {
|
||||
skip: cursor ? 1 : 0,
|
||||
cursor: cursor ? { id: cursor } : undefined,
|
||||
});
|
||||
|
||||
const teamCollections = res.map((teamCollection) =>
|
||||
this.cast(teamCollection),
|
||||
);
|
||||
|
||||
return teamCollections;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -497,7 +470,6 @@ export class TeamCollectionService {
|
||||
async createCollection(
|
||||
teamID: string,
|
||||
title: string,
|
||||
data: string | null = null,
|
||||
parentTeamCollectionID: string | null,
|
||||
) {
|
||||
const isTitleValid = isValidLength(title, this.TITLE_LENGTH);
|
||||
@@ -509,13 +481,6 @@ export class TeamCollectionService {
|
||||
if (O.isNone(isOwner)) return E.left(TEAM_NOT_OWNER);
|
||||
}
|
||||
|
||||
if (data === '') return E.left(TEAM_COLL_DATA_INVALID);
|
||||
if (data) {
|
||||
const jsonReq = stringToJson(data);
|
||||
if (E.isLeft(jsonReq)) return E.left(TEAM_COLL_DATA_INVALID);
|
||||
data = jsonReq.right;
|
||||
}
|
||||
|
||||
const isParent = parentTeamCollectionID
|
||||
? {
|
||||
connect: {
|
||||
@@ -533,23 +498,18 @@ export class TeamCollectionService {
|
||||
},
|
||||
},
|
||||
parent: isParent,
|
||||
data: data ?? undefined,
|
||||
orderIndex: !parentTeamCollectionID
|
||||
? (await this.getRootCollectionsCount(teamID)) + 1
|
||||
: (await this.getChildCollectionsCount(parentTeamCollectionID)) + 1,
|
||||
},
|
||||
});
|
||||
|
||||
this.pubsub.publish(
|
||||
`team_coll/${teamID}/coll_added`,
|
||||
this.cast(teamCollection),
|
||||
);
|
||||
this.pubsub.publish(`team_coll/${teamID}/coll_added`, teamCollection);
|
||||
|
||||
return E.right(this.cast(teamCollection));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use updateTeamCollection method instead
|
||||
* Update the title of a TeamCollection
|
||||
*
|
||||
* @param collectionID The Collection ID
|
||||
@@ -572,10 +532,10 @@ export class TeamCollectionService {
|
||||
|
||||
this.pubsub.publish(
|
||||
`team_coll/${updatedTeamCollection.teamID}/coll_updated`,
|
||||
this.cast(updatedTeamCollection),
|
||||
updatedTeamCollection,
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedTeamCollection));
|
||||
return E.right(updatedTeamCollection);
|
||||
} catch (error) {
|
||||
return E.left(TEAM_COLL_NOT_FOUND);
|
||||
}
|
||||
@@ -734,8 +694,8 @@ export class TeamCollectionService {
|
||||
* @returns An Option of boolean, is parent or not
|
||||
*/
|
||||
private async isParent(
|
||||
collection: DBTeamCollection,
|
||||
destCollection: DBTeamCollection,
|
||||
collection: TeamCollection,
|
||||
destCollection: TeamCollection,
|
||||
): Promise<O.Option<boolean>> {
|
||||
//* Recursively check if collection is a parent by going up the tree of child-parent collections until we reach a root collection i.e parentID === null
|
||||
//* Valid condition, isParent returns false
|
||||
@@ -1011,49 +971,4 @@ export class TeamCollectionService {
|
||||
const teamCollectionsCount = this.prisma.teamCollection.count();
|
||||
return teamCollectionsCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update Team Collection details
|
||||
*
|
||||
* @param collectionID Collection ID
|
||||
* @param collectionData new header data in a JSONified string form
|
||||
* @param newTitle New title of the collection
|
||||
* @returns Updated TeamCollection
|
||||
*/
|
||||
async updateTeamCollection(
|
||||
collectionID: string,
|
||||
collectionData: string = null,
|
||||
newTitle: string = null,
|
||||
) {
|
||||
try {
|
||||
if (newTitle != null) {
|
||||
const isTitleValid = isValidLength(newTitle, this.TITLE_LENGTH);
|
||||
if (!isTitleValid) return E.left(TEAM_COLL_SHORT_TITLE);
|
||||
}
|
||||
|
||||
if (collectionData === '') return E.left(TEAM_COLL_DATA_INVALID);
|
||||
if (collectionData) {
|
||||
const jsonReq = stringToJson(collectionData);
|
||||
if (E.isLeft(jsonReq)) return E.left(TEAM_COLL_DATA_INVALID);
|
||||
collectionData = jsonReq.right;
|
||||
}
|
||||
|
||||
const updatedTeamCollection = await this.prisma.teamCollection.update({
|
||||
where: { id: collectionID },
|
||||
data: {
|
||||
data: collectionData ?? undefined,
|
||||
title: newTitle ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
this.pubsub.publish(
|
||||
`team_coll/${updatedTeamCollection.teamID}/coll_updated`,
|
||||
this.cast(updatedTeamCollection),
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedTeamCollection));
|
||||
} catch (e) {
|
||||
return E.left(TEAM_COLL_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,6 @@ const teamCollection: DbTeamCollection = {
|
||||
id: 'team-coll-1',
|
||||
parentID: null,
|
||||
teamID: team.id,
|
||||
data: {},
|
||||
title: 'Team Collection 1',
|
||||
orderIndex: 1,
|
||||
createdOn: new Date(),
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// This interface defines how data will be received from the app when we are importing Hoppscotch collections
|
||||
export interface CollectionFolder {
|
||||
id?: string;
|
||||
folders: CollectionFolder[];
|
||||
requests: any[];
|
||||
name: string;
|
||||
data?: string;
|
||||
}
|
||||
|
||||
@@ -6,13 +6,6 @@ import { PaginationArgs } from 'src/types/input-types.args';
|
||||
export class CreateRootUserCollectionArgs {
|
||||
@Field({ name: 'title', description: 'Title of the new user collection' })
|
||||
title: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
@ArgsType()
|
||||
export class CreateChildUserCollectionArgs {
|
||||
@@ -24,13 +17,6 @@ export class CreateChildUserCollectionArgs {
|
||||
description: 'ID of the parent to the new user collection',
|
||||
})
|
||||
parentUserCollectionID: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
|
||||
@ArgsType()
|
||||
@@ -109,26 +95,3 @@ export class ImportUserCollectionsFromJSONArgs {
|
||||
})
|
||||
parentCollectionID?: string;
|
||||
}
|
||||
|
||||
@ArgsType()
|
||||
export class UpdateUserCollectionsArgs {
|
||||
@Field(() => ID, {
|
||||
name: 'userCollectionID',
|
||||
description: 'ID of the user collection',
|
||||
})
|
||||
userCollectionID: string;
|
||||
|
||||
@Field({
|
||||
name: 'newTitle',
|
||||
description: 'The updated title of the user collection',
|
||||
nullable: true,
|
||||
})
|
||||
newTitle: string;
|
||||
|
||||
@Field({
|
||||
name: 'data',
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
}
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
MoveUserCollectionArgs,
|
||||
RenameUserCollectionsArgs,
|
||||
UpdateUserCollectionArgs,
|
||||
UpdateUserCollectionsArgs,
|
||||
} from './input-type.args';
|
||||
import { ReqType } from 'src/types/RequestTypes';
|
||||
import * as E from 'fp-ts/Either';
|
||||
@@ -143,13 +142,7 @@ export class UserCollectionResolver {
|
||||
);
|
||||
|
||||
if (E.isLeft(userCollection)) throwErr(userCollection.left);
|
||||
return <UserCollection>{
|
||||
...userCollection.right,
|
||||
userID: userCollection.right.userUid,
|
||||
data: !userCollection.right.data
|
||||
? null
|
||||
: JSON.stringify(userCollection.right.data),
|
||||
};
|
||||
return userCollection.right;
|
||||
}
|
||||
|
||||
@Query(() => UserCollectionExportJSONData, {
|
||||
@@ -198,7 +191,6 @@ export class UserCollectionResolver {
|
||||
await this.userCollectionService.createUserCollection(
|
||||
user,
|
||||
args.title,
|
||||
args.data,
|
||||
null,
|
||||
ReqType.REST,
|
||||
);
|
||||
@@ -220,7 +212,6 @@ export class UserCollectionResolver {
|
||||
await this.userCollectionService.createUserCollection(
|
||||
user,
|
||||
args.title,
|
||||
args.data,
|
||||
null,
|
||||
ReqType.GQL,
|
||||
);
|
||||
@@ -241,7 +232,6 @@ export class UserCollectionResolver {
|
||||
await this.userCollectionService.createUserCollection(
|
||||
user,
|
||||
args.title,
|
||||
args.data,
|
||||
args.parentUserCollectionID,
|
||||
ReqType.GQL,
|
||||
);
|
||||
@@ -262,7 +252,6 @@ export class UserCollectionResolver {
|
||||
await this.userCollectionService.createUserCollection(
|
||||
user,
|
||||
args.title,
|
||||
args.data,
|
||||
args.parentUserCollectionID,
|
||||
ReqType.REST,
|
||||
);
|
||||
@@ -370,26 +359,6 @@ export class UserCollectionResolver {
|
||||
return importedCollection.right;
|
||||
}
|
||||
|
||||
@Mutation(() => UserCollection, {
|
||||
description: 'Update a UserCollection',
|
||||
})
|
||||
@UseGuards(GqlAuthGuard)
|
||||
async updateUserCollection(
|
||||
@GqlUser() user: AuthUser,
|
||||
@Args() args: UpdateUserCollectionsArgs,
|
||||
) {
|
||||
const updatedUserCollection =
|
||||
await this.userCollectionService.updateUserCollection(
|
||||
args.newTitle,
|
||||
args.data,
|
||||
args.userCollectionID,
|
||||
user.uid,
|
||||
);
|
||||
|
||||
if (E.isLeft(updatedUserCollection)) throwErr(updatedUserCollection.left);
|
||||
return updatedUserCollection.right;
|
||||
}
|
||||
|
||||
// Subscriptions
|
||||
@Subscription(() => UserCollection, {
|
||||
description: 'Listen for User Collection Creation',
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
USER_NOT_FOUND,
|
||||
USER_NOT_OWNER,
|
||||
USER_COLL_INVALID_JSON,
|
||||
USER_COLL_DATA_INVALID,
|
||||
} from 'src/errors';
|
||||
import { PrismaService } from 'src/prisma/prisma.service';
|
||||
import { AuthUser } from 'src/types/AuthUser';
|
||||
@@ -44,12 +43,8 @@ export class UserCollectionService {
|
||||
*/
|
||||
private cast(collection: UserCollection) {
|
||||
return <UserCollectionModel>{
|
||||
id: collection.id,
|
||||
title: collection.title,
|
||||
type: collection.type,
|
||||
parentID: collection.parentID,
|
||||
...collection,
|
||||
userID: collection.userUid,
|
||||
data: !collection.data ? null : JSON.stringify(collection.data),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -151,7 +146,7 @@ export class UserCollectionService {
|
||||
},
|
||||
});
|
||||
|
||||
return !parent ? null : this.cast(parent);
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -169,7 +164,7 @@ export class UserCollectionService {
|
||||
take: number,
|
||||
type: ReqType,
|
||||
) {
|
||||
const res = await this.prisma.userCollection.findMany({
|
||||
return this.prisma.userCollection.findMany({
|
||||
where: {
|
||||
parentID: collectionID,
|
||||
type: type,
|
||||
@@ -181,12 +176,6 @@ export class UserCollectionService {
|
||||
skip: cursor ? 1 : 0,
|
||||
cursor: cursor ? { id: cursor } : undefined,
|
||||
});
|
||||
|
||||
const childCollections = res.map((childCollection) =>
|
||||
this.cast(childCollection),
|
||||
);
|
||||
|
||||
return childCollections;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,20 +211,12 @@ export class UserCollectionService {
|
||||
async createUserCollection(
|
||||
user: AuthUser,
|
||||
title: string,
|
||||
data: string | null = null,
|
||||
parentUserCollectionID: string | null,
|
||||
type: ReqType,
|
||||
) {
|
||||
const isTitleValid = isValidLength(title, this.TITLE_LENGTH);
|
||||
if (!isTitleValid) return E.left(USER_COLL_SHORT_TITLE);
|
||||
|
||||
if (data === '') return E.left(USER_COLL_DATA_INVALID);
|
||||
if (data) {
|
||||
const jsonReq = stringToJson(data);
|
||||
if (E.isLeft(jsonReq)) return E.left(USER_COLL_DATA_INVALID);
|
||||
data = jsonReq.right;
|
||||
}
|
||||
|
||||
// If creating a child collection
|
||||
if (parentUserCollectionID !== null) {
|
||||
const parentCollection = await this.getUserCollection(
|
||||
@@ -270,19 +251,15 @@ export class UserCollectionService {
|
||||
},
|
||||
},
|
||||
parent: isParent,
|
||||
data: data ?? undefined,
|
||||
orderIndex: !parentUserCollectionID
|
||||
? (await this.getRootCollectionsCount(user.uid)) + 1
|
||||
: (await this.getChildCollectionsCount(parentUserCollectionID)) + 1,
|
||||
},
|
||||
});
|
||||
|
||||
await this.pubsub.publish(
|
||||
`user_coll/${user.uid}/created`,
|
||||
this.cast(userCollection),
|
||||
);
|
||||
await this.pubsub.publish(`user_coll/${user.uid}/created`, userCollection);
|
||||
|
||||
return E.right(this.cast(userCollection));
|
||||
return E.right(userCollection);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -299,7 +276,7 @@ export class UserCollectionService {
|
||||
take: number,
|
||||
type: ReqType,
|
||||
) {
|
||||
const res = await this.prisma.userCollection.findMany({
|
||||
return this.prisma.userCollection.findMany({
|
||||
where: {
|
||||
userUid: user.uid,
|
||||
parentID: null,
|
||||
@@ -312,12 +289,6 @@ export class UserCollectionService {
|
||||
skip: cursor ? 1 : 0,
|
||||
cursor: cursor ? { id: cursor } : undefined,
|
||||
});
|
||||
|
||||
const userCollections = res.map((childCollection) =>
|
||||
this.cast(childCollection),
|
||||
);
|
||||
|
||||
return userCollections;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -336,7 +307,7 @@ export class UserCollectionService {
|
||||
take: number,
|
||||
type: ReqType,
|
||||
) {
|
||||
const res = await this.prisma.userCollection.findMany({
|
||||
return this.prisma.userCollection.findMany({
|
||||
where: {
|
||||
userUid: user.uid,
|
||||
parentID: userCollectionID,
|
||||
@@ -346,16 +317,9 @@ export class UserCollectionService {
|
||||
skip: cursor ? 1 : 0,
|
||||
cursor: cursor ? { id: cursor } : undefined,
|
||||
});
|
||||
|
||||
const childCollections = res.map((childCollection) =>
|
||||
this.cast(childCollection),
|
||||
);
|
||||
|
||||
return childCollections;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use updateUserCollection method instead
|
||||
* Update the title of a UserCollection
|
||||
*
|
||||
* @param newTitle The new title of collection
|
||||
@@ -387,10 +351,10 @@ export class UserCollectionService {
|
||||
|
||||
this.pubsub.publish(
|
||||
`user_coll/${updatedUserCollection.userUid}/updated`,
|
||||
this.cast(updatedUserCollection),
|
||||
updatedUserCollection,
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedUserCollection));
|
||||
return E.right(updatedUserCollection);
|
||||
} catch (error) {
|
||||
return E.left(USER_COLL_NOT_FOUND);
|
||||
}
|
||||
@@ -627,10 +591,10 @@ export class UserCollectionService {
|
||||
|
||||
this.pubsub.publish(
|
||||
`user_coll/${collection.right.userUid}/moved`,
|
||||
this.cast(updatedCollection.right),
|
||||
updatedCollection.right,
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedCollection.right));
|
||||
return E.right(updatedCollection.right);
|
||||
}
|
||||
|
||||
// destCollectionID != null i.e move into another collection
|
||||
@@ -678,10 +642,10 @@ export class UserCollectionService {
|
||||
|
||||
this.pubsub.publish(
|
||||
`user_coll/${collection.right.userUid}/moved`,
|
||||
this.cast(updatedCollection.right),
|
||||
updatedCollection.right,
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedCollection.right));
|
||||
return E.right(updatedCollection.right);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -882,7 +846,6 @@ export class UserCollectionService {
|
||||
...(x.request as Record<string, unknown>), // type casting x.request of type Prisma.JSONValue to an object to enable spread
|
||||
};
|
||||
}),
|
||||
data: JSON.stringify(collection.right.data),
|
||||
};
|
||||
|
||||
return E.right(result);
|
||||
@@ -955,7 +918,6 @@ export class UserCollectionService {
|
||||
...(x.request as Record<string, unknown>), // type casting x.request of type Prisma.JSONValue to an object to enable spread
|
||||
};
|
||||
}),
|
||||
data: JSON.stringify(parentCollection.right.data),
|
||||
}),
|
||||
collectionType: parentCollection.right.type,
|
||||
});
|
||||
@@ -1009,7 +971,6 @@ export class UserCollectionService {
|
||||
this.generatePrismaQueryObj(f, userID, index + 1, reqType),
|
||||
),
|
||||
},
|
||||
data: folder.data ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1079,63 +1040,10 @@ export class UserCollectionService {
|
||||
),
|
||||
);
|
||||
|
||||
userCollections.forEach((collection) =>
|
||||
this.pubsub.publish(`user_coll/${userID}/created`, this.cast(collection)),
|
||||
userCollections.forEach((x) =>
|
||||
this.pubsub.publish(`user_coll/${userID}/created`, x),
|
||||
);
|
||||
|
||||
return E.right(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a UserCollection
|
||||
*
|
||||
* @param newTitle The new title of collection
|
||||
* @param userCollectionID The Collection Id
|
||||
* @param userID The User UID
|
||||
* @returns An Either of the updated UserCollection
|
||||
*/
|
||||
async updateUserCollection(
|
||||
newTitle: string = null,
|
||||
collectionData: string | null = null,
|
||||
userCollectionID: string,
|
||||
userID: string,
|
||||
) {
|
||||
if (collectionData === '') return E.left(USER_COLL_DATA_INVALID);
|
||||
|
||||
if (collectionData) {
|
||||
const jsonReq = stringToJson(collectionData);
|
||||
if (E.isLeft(jsonReq)) return E.left(USER_COLL_DATA_INVALID);
|
||||
collectionData = jsonReq.right;
|
||||
}
|
||||
|
||||
if (newTitle != null) {
|
||||
const isTitleValid = isValidLength(newTitle, this.TITLE_LENGTH);
|
||||
if (!isTitleValid) return E.left(USER_COLL_SHORT_TITLE);
|
||||
}
|
||||
|
||||
// Check to see is the collection belongs to the user
|
||||
const isOwner = await this.isOwnerCheck(userCollectionID, userID);
|
||||
if (O.isNone(isOwner)) return E.left(USER_NOT_OWNER);
|
||||
|
||||
try {
|
||||
const updatedUserCollection = await this.prisma.userCollection.update({
|
||||
where: {
|
||||
id: userCollectionID,
|
||||
},
|
||||
data: {
|
||||
data: collectionData ?? undefined,
|
||||
title: newTitle ?? undefined,
|
||||
},
|
||||
});
|
||||
|
||||
this.pubsub.publish(
|
||||
`user_coll/${updatedUserCollection.userUid}/updated`,
|
||||
this.cast(updatedUserCollection),
|
||||
);
|
||||
|
||||
return E.right(this.cast(updatedUserCollection));
|
||||
} catch (error) {
|
||||
return E.left(USER_COLL_NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,6 @@ export class UserCollection {
|
||||
})
|
||||
title: string;
|
||||
|
||||
@Field({
|
||||
description: 'JSON string representing the collection data',
|
||||
nullable: true,
|
||||
})
|
||||
data: string;
|
||||
|
||||
@Field(() => ReqType, {
|
||||
description: 'Type of the user collection',
|
||||
})
|
||||
|
||||
@@ -57,7 +57,7 @@ module.exports = {
|
||||
{
|
||||
name: "localStorage",
|
||||
message:
|
||||
"Do not use 'localStorage' directly. Please use the PersistenceService",
|
||||
"Do not use 'localStorage' directly. Please use localpersistence.ts functions or stores",
|
||||
},
|
||||
],
|
||||
// window.localStorage block
|
||||
@@ -66,7 +66,7 @@ module.exports = {
|
||||
{
|
||||
selector: "CallExpression[callee.object.property.name='localStorage']",
|
||||
message:
|
||||
"Do not use 'localStorage' directly. Please use the PersistenceService",
|
||||
"Do not use 'localStorage' directly. Please use localpersistence.ts functions or stores",
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
{
|
||||
"action": {
|
||||
"add": "Add",
|
||||
"autoscroll": "Autoscroll",
|
||||
"cancel": "Cancel",
|
||||
"choose_file": "Choose a file",
|
||||
@@ -55,28 +54,9 @@
|
||||
"new": "Add new",
|
||||
"star": "Add star"
|
||||
},
|
||||
"cookies": {
|
||||
"modal": {
|
||||
"new_domain_name": "New domain name",
|
||||
"set": "Set a cookie",
|
||||
"cookie_string": "Cookie string",
|
||||
"enter_cookie_string": "Enter cookie string",
|
||||
"cookie_name": "Name",
|
||||
"cookie_value": "Value",
|
||||
"cookie_path": "Path",
|
||||
"cookie_expires": "Expires",
|
||||
"managed_tab": "Managed",
|
||||
"raw_tab": "Raw",
|
||||
"interceptor_no_support": "Your currently selected interceptor does not support cookies. Select a different Interceptor and try again.",
|
||||
"empty_domains": "Domain list is empty",
|
||||
"empty_domain": "Domain is empty",
|
||||
"no_cookies_in_domain": "No cookies set for this domain"
|
||||
}
|
||||
},
|
||||
"app": {
|
||||
"chat_with_us": "Chat with us",
|
||||
"contact_us": "Contact us",
|
||||
"cookies": "Cookies",
|
||||
"copy": "Copy",
|
||||
"copy_user_id": "Copy User Auth Token",
|
||||
"developer_option": "Developer options",
|
||||
@@ -139,21 +119,7 @@
|
||||
"password": "Password",
|
||||
"token": "Token",
|
||||
"type": "Authorization Type",
|
||||
"username": "Username",
|
||||
"oauth": {
|
||||
"token_generation_oidc_discovery_failed": "Failure on token generation: OpenID Connect Discovery Failed",
|
||||
"something_went_wrong_on_token_generation": "Something went wrong on token generation",
|
||||
"redirect_auth_server_returned_error": "Auth Server returned an error state",
|
||||
"redirect_no_auth_code": "No Authorization Code present in the redirect",
|
||||
"redirect_invalid_state": "Invalid State value present in the redirect",
|
||||
"redirect_no_token_endpoint": "No Token Endpoint Defined",
|
||||
"redirect_no_client_id": "No Client ID defined",
|
||||
"redirect_no_client_secret": "No Client Secret Defined",
|
||||
"redirect_no_code_verifier": "No Code Verifier Defined",
|
||||
"redirect_auth_token_request_failed": "Request to get the auth token failed",
|
||||
"redirect_auth_token_request_invalid_response": "Invalid Response from the Token Endpoint when requesting for an auth token",
|
||||
"something_went_wrong_on_oauth_redirect": "Something went wrong during OAuth Redirect"
|
||||
}
|
||||
"username": "Username"
|
||||
},
|
||||
"collection": {
|
||||
"created": "Collection created",
|
||||
@@ -271,7 +237,6 @@
|
||||
"error": {
|
||||
"browser_support_sse": "This browser doesn't seems to have Server Sent Events support.",
|
||||
"check_console_details": "Check console log for details.",
|
||||
"check_how_to_add_origin": "Check how you can add an origin",
|
||||
"curl_invalid_format": "cURL is not formatted properly",
|
||||
"danger_zone": "Danger zone",
|
||||
"delete_account": "Your account is currently an owner in these teams:",
|
||||
@@ -292,7 +257,6 @@
|
||||
"no_environments_to_export": "No environments to export. Please create an environment to get started.",
|
||||
"no_results_found": "No matches found",
|
||||
"page_not_found": "This page could not be found",
|
||||
"please_install_extension": "Please install the extension and add origin to the extension.",
|
||||
"proxy_error": "Proxy error",
|
||||
"script_fail": "Could not execute pre-request script",
|
||||
"something_went_wrong": "Something went wrong",
|
||||
@@ -497,8 +461,7 @@
|
||||
"enter_curl": "Enter cURL command",
|
||||
"generate_code": "Generate code",
|
||||
"generated_code": "Generated code",
|
||||
"go_to_authorization_tab": "Go to Authorization tab",
|
||||
"go_to_body_tab": "Go to Body tab",
|
||||
"go_to_authorization_tab": "Go to Authorization",
|
||||
"header_list": "Header List",
|
||||
"invalid_name": "Please provide a name for the request",
|
||||
"method": "Method",
|
||||
@@ -600,7 +563,6 @@
|
||||
"use_experimental_url_bar": "Use experimental URL bar with environment highlighting",
|
||||
"user": "User",
|
||||
"verified_email": "Verified email",
|
||||
"additional": "Additional Settings",
|
||||
"verify_email": "Verify email"
|
||||
},
|
||||
"shortcodes": {
|
||||
@@ -802,7 +764,7 @@
|
||||
"published_error": "Something went wrong while publishing msg: {topic} to topic: {message}",
|
||||
"published_message": "Published message: {message} to topic: {topic}",
|
||||
"reconnection_error": "Failed to reconnect",
|
||||
"show": "Show",
|
||||
"show":"Show",
|
||||
"subscribed_failed": "Failed to subscribe to topic: {topic}",
|
||||
"subscribed_success": "Successfully subscribed to topic: {topic}",
|
||||
"unsubscribed_failed": "Failed to unsubscribe from topic: {topic}",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@hoppscotch/common",
|
||||
"private": true,
|
||||
"version": "2023.8.4-1",
|
||||
"version": "2023.8.3",
|
||||
"scripts": {
|
||||
"dev": "pnpm exec npm-run-all -p -l dev:*",
|
||||
"test": "vitest --run",
|
||||
@@ -27,7 +27,7 @@
|
||||
"@codemirror/lang-javascript": "^6.2.1",
|
||||
"@codemirror/lang-json": "^6.0.1",
|
||||
"@codemirror/lang-xml": "^6.0.2",
|
||||
"@codemirror/language": "6.9.0",
|
||||
"@codemirror/language": "^6.9.2",
|
||||
"@codemirror/legacy-modes": "^6.3.3",
|
||||
"@codemirror/lint": "^6.4.2",
|
||||
"@codemirror/search": "^6.5.4",
|
||||
@@ -52,7 +52,6 @@
|
||||
"acorn-walk": "^8.2.0",
|
||||
"axios": "^1.4.0",
|
||||
"buffer": "^6.0.3",
|
||||
"cookie-es": "^1.0.0",
|
||||
"dioc": "workspace:^",
|
||||
"esprima": "^4.0.1",
|
||||
"events": "^3.3.0",
|
||||
@@ -77,8 +76,6 @@
|
||||
"process": "^0.11.10",
|
||||
"qs": "^6.11.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"set-cookie-parser": "^2.6.0",
|
||||
"set-cookie-parser-es": "^1.0.5",
|
||||
"socket.io-client-v2": "npm:socket.io-client@^2.4.0",
|
||||
"socket.io-client-v3": "npm:socket.io-client@^3.1.3",
|
||||
"socket.io-client-v4": "npm:socket.io-client@^4.4.1",
|
||||
@@ -92,7 +89,6 @@
|
||||
"url": "^0.11.1",
|
||||
"util": "^0.12.5",
|
||||
"uuid": "^9.0.0",
|
||||
"verzod": "^0.2.0",
|
||||
"vue": "^3.3.4",
|
||||
"vue-i18n": "^9.2.2",
|
||||
"vue-pdf-embed": "^1.1.6",
|
||||
@@ -102,8 +98,7 @@
|
||||
"wonka": "^6.3.4",
|
||||
"workbox-window": "^7.0.0",
|
||||
"xml-formatter": "^3.5.0",
|
||||
"yargs-parser": "^21.1.1",
|
||||
"zod": "^3.22.4"
|
||||
"yargs-parser": "^21.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
|
||||
@@ -144,19 +139,19 @@
|
||||
"eslint-plugin-vue": "^9.17.0",
|
||||
"glob": "^10.3.10",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"openapi-types": "^12.1.3",
|
||||
"postcss": "^8.4.23",
|
||||
"prettier-plugin-tailwindcss": "^0.5.6",
|
||||
"tailwindcss": "^3.3.2",
|
||||
"vite-plugin-fonts": "^0.6.0",
|
||||
"openapi-types": "^12.1.3",
|
||||
"rollup-plugin-polyfill-node": "^0.12.0",
|
||||
"sass": "^1.66.0",
|
||||
"tailwindcss": "^3.3.2",
|
||||
"typescript": "^5.1.6",
|
||||
"unplugin-fonts": "^1.0.3",
|
||||
"unplugin-icons": "^0.16.5",
|
||||
"unplugin-vue-components": "^0.25.1",
|
||||
"vite": "^4.4.9",
|
||||
"vite-plugin-checker": "^0.6.1",
|
||||
"vite-plugin-fonts": "^0.6.0",
|
||||
"vite-plugin-html-config": "^1.0.11",
|
||||
"vite-plugin-inspect": "^0.7.38",
|
||||
"vite-plugin-pages": "^0.31.0",
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="156" height="32" fill="none"><rect width="156" height="32" fill="#000" rx="4"/><text xmlns="http://www.w3.org/2000/svg" x="50%" y="50%" fill="#fff" dominant-baseline="central" font-family="Helvetica,sans-serif" font-size="12" font-weight="bold" text-anchor="middle" text-rendering="geometricPrecision">▶ Run in Hoppscotch</text></svg>
|
||||
|
Before Width: | Height: | Size: 386 B |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="156" height="32" fill="none"><rect width="156" height="32" fill="#fff" rx="4"/><text xmlns="http://www.w3.org/2000/svg" x="50%" y="50%" fill="#000" dominant-baseline="central" font-family="Helvetica,sans-serif" font-size="12" font-weight="bold" text-anchor="middle" text-rendering="geometricPrecision">▶ Run in Hoppscotch</text></svg>
|
||||
|
Before Width: | Height: | Size: 386 B |
|
Before Width: | Height: | Size: 354 KiB After Width: | Height: | Size: 926 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 462 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 624 B After Width: | Height: | Size: 400 B |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 871 B |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 360 KiB After Width: | Height: | Size: 510 KiB |
|
Before Width: | Height: | Size: 385 KiB After Width: | Height: | Size: 535 KiB |
|
Before Width: | Height: | Size: 178 KiB After Width: | Height: | Size: 60 KiB |
@@ -1,50 +1 @@
|
||||
<svg width="824" height="824" viewBox="0 0 824 824" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="824" height="824" rx="184" fill="#08110F"/>
|
||||
<rect width="824" height="824" rx="184" fill="url(#paint0_radial_0_21)" fill-opacity="0.5"/>
|
||||
<path d="M435.425 463.217C429.441 476.657 411.033 481.515 394.309 474.07C377.585 466.624 368.879 449.693 374.863 436.253C380.846 422.813 399.254 417.954 415.978 425.4C432.702 432.846 441.409 449.777 435.425 463.217Z" fill="url(#paint1_linear_0_21)"/>
|
||||
<path d="M435.425 463.217C429.441 476.657 411.033 481.515 394.309 474.07C377.585 466.624 368.879 449.693 374.863 436.253C380.846 422.813 399.254 417.954 415.978 425.4C432.702 432.846 441.409 449.777 435.425 463.217Z" fill="url(#paint2_radial_0_21)" style="mix-blend-mode:soft-light"/>
|
||||
<path d="M535.563 521.172C553.071 526.191 570.536 518.856 574.571 504.789C578.606 490.722 567.684 475.251 550.175 470.232C532.666 465.213 515.201 472.548 511.166 486.615C507.131 500.682 518.054 516.153 535.563 521.172Z" fill="url(#paint3_linear_0_21)"/>
|
||||
<path d="M535.563 521.172C553.071 526.191 570.536 518.856 574.571 504.789C578.606 490.722 567.684 475.251 550.175 470.232C532.666 465.213 515.201 472.548 511.166 486.615C507.131 500.682 518.054 516.153 535.563 521.172Z" fill="url(#paint4_radial_0_21)" style="mix-blend-mode:soft-light"/>
|
||||
<path d="M292.782 355.633C308.227 365.286 314.462 383.173 306.709 395.584C298.955 407.995 280.149 410.231 264.704 400.578C249.258 390.924 243.023 373.037 250.777 360.626C258.53 348.215 277.337 345.98 292.782 355.633Z" fill="url(#paint5_linear_0_21)"/>
|
||||
<path d="M292.782 355.633C308.227 365.286 314.462 383.173 306.709 395.584C298.955 407.995 280.149 410.231 264.704 400.578C249.258 390.924 243.023 373.037 250.777 360.626C258.53 348.215 277.337 345.98 292.782 355.633Z" fill="url(#paint6_radial_0_21)" style="mix-blend-mode:soft-light"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M502.355 231.325C581.373 266.506 632.095 343.263 634.119 429.03C680.633 465.639 726.858 516.883 705.36 565.168C681.25 619.319 595.382 617.091 497.781 589.689C450.767 615.718 392.444 620.168 339.689 596.68C286.934 573.192 251.229 526.908 239.1 474.517C153.428 420.321 94.3151 357.999 118.425 303.847C139.923 255.562 208.935 255.626 267.265 265.697C332.356 209.81 423.338 196.144 502.355 231.325ZM159.38 322.082C147.667 348.389 210.578 423.052 382.845 499.751C555.111 576.449 652.693 573.241 664.405 546.934C674.099 525.16 634.213 483.308 588.537 450.878C553.009 425.484 504.344 397.494 440.864 369.231C423.586 361.538 416.839 341.008 424.104 324.691C431.369 308.374 447.329 297.463 480.93 295.91C496.747 295.862 498.823 291.476 499.546 287.716C500.442 281.915 492.401 276.002 484.108 272.31C418.17 242.953 337.453 255.265 281.503 314.178C226.84 301.933 169.074 300.309 159.38 322.082Z" fill="url(#paint7_linear_0_21)"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M502.355 231.325C581.373 266.506 632.095 343.263 634.119 429.03C680.633 465.639 726.858 516.883 705.36 565.168C681.25 619.319 595.382 617.091 497.781 589.689C450.767 615.718 392.444 620.168 339.689 596.68C286.934 573.192 251.229 526.908 239.1 474.517C153.428 420.321 94.3151 357.999 118.425 303.847C139.923 255.562 208.935 255.626 267.265 265.697C332.356 209.81 423.338 196.144 502.355 231.325ZM159.38 322.082C147.667 348.389 210.578 423.052 382.845 499.751C555.111 576.449 652.693 573.241 664.405 546.934C674.099 525.16 634.213 483.308 588.537 450.878C553.009 425.484 504.344 397.494 440.864 369.231C423.586 361.538 416.839 341.008 424.104 324.691C431.369 308.374 447.329 297.463 480.93 295.91C496.747 295.862 498.823 291.476 499.546 287.716C500.442 281.915 492.401 276.002 484.108 272.31C418.17 242.953 337.453 255.265 281.503 314.178C226.84 301.933 169.074 300.309 159.38 322.082Z" fill="url(#paint8_radial_0_21)" style="mix-blend-mode:soft-light"/>
|
||||
<defs>
|
||||
<radialGradient id="paint0_radial_0_21" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(814.524 12.36) rotate(125.613) scale(1089.59 1210.34)">
|
||||
<stop stop-color="#00D196" stop-opacity="0.5"/>
|
||||
<stop offset="0.996771" stop-color="#00D196" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="paint1_linear_0_21" x1="411.893" y1="212" x2="411.893" y2="612" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#00D196"/>
|
||||
<stop offset="1" stop-color="#00B381"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="paint2_radial_0_21" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(644.721 344.481) rotate(159.984) scale(631.37 385.135)">
|
||||
<stop stop-color="white"/>
|
||||
<stop offset="1" stop-color="white" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="paint3_linear_0_21" x1="411.893" y1="212" x2="411.893" y2="612" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#00D196"/>
|
||||
<stop offset="1" stop-color="#00B381"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="paint4_radial_0_21" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(644.721 344.481) rotate(159.984) scale(631.37 385.135)">
|
||||
<stop stop-color="white"/>
|
||||
<stop offset="1" stop-color="white" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="paint5_linear_0_21" x1="411.893" y1="212" x2="411.893" y2="612" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#00D196"/>
|
||||
<stop offset="1" stop-color="#00B381"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="paint6_radial_0_21" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(644.721 344.481) rotate(159.984) scale(631.37 385.135)">
|
||||
<stop stop-color="white"/>
|
||||
<stop offset="1" stop-color="white" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="paint7_linear_0_21" x1="411.893" y1="212" x2="411.893" y2="612" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#00D196"/>
|
||||
<stop offset="1" stop-color="#00B381"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="paint8_radial_0_21" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(644.721 344.481) rotate(159.984) scale(631.37 385.135)">
|
||||
<stop stop-color="white"/>
|
||||
<stop offset="1" stop-color="white" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" fill="none"><path fill="#10B981" d="M0 0h512v512H0z"/><circle cx="197.76" cy="157.84" r="10" fill="#fff" fill-opacity=".75"/><circle cx="259.76" cy="161.84" r="12" fill="#fff" fill-opacity=".75"/><circle cx="319.76" cy="177.84" r="10" fill="#fff" fill-opacity=".75"/><path d="M344.963 235.676c2.075-12.698-38.872-29.804-90.967-38.094-52.09-8.296-96.404-4.665-98.48 8.033-.257 1.035 0 1.812.263 2.853-1.298-.521-76.714 211.212-76.714 211.212H364.14s-17.621-181.414-20.211-181.414c.515-.772 1.035-1.549 1.035-2.59Z" fill="url(#a)"/><path d="M314.902 227.386c-1.298 8.033-30.839 9.845-66.343 4.402-35.247-5.7-62.982-16.843-61.684-24.618.521-2.59 3.888-4.665 9.331-5.7-18.141.777-30.062 4.145-31.096 9.845-1.555 10.628 34.726 25.139 81.373 32.657 46.647 7.512 85.782 4.665 87.594-5.7 1.041-6.226-9.33-12.961-26.431-19.439 4.923 2.847 7.513 5.957 7.256 8.553Z" fill="#A7F3D0" fill-opacity=".5"/><path d="M333.557 157.413c-3.104-32.137-27.729-59.351-60.9-64.53-33.172-5.186-64.531 12.954-77.749 42.238 21.251 1.298 44.057 3.631 67.904 7.518 25.396 3.888 49.237 9.074 70.745 14.774Z" fill="url(#b)"/><path d="M74.142 158.002c-2.59 15.808 30.319 35.247 81.894 51.055-.257-1.04-.257-1.818-.257-2.853 2.07-12.698 46.127-16.328 98.48-8.032 52.347 8.29 93.037 25.396 90.961 38.094-.257 1.04-.514 1.818-1.035 2.589 53.645.778 90.968-7.512 93.557-23.32 3.625-24.104-74.638-56.498-174.93-72.306-100.555-15.808-185.045-9.331-188.67 14.773Zm115.586-1.298c.778-4.145 4.665-7.255 8.81-6.477 4.145.777 7.256 4.665 6.478 8.81-.52 4.145-4.665 6.998-8.81 6.478-4.145-.778-7.255-4.666-6.478-8.811Zm59.866 4.145c.777-5.7 6.22-9.587 11.92-8.547 5.7.778 9.588 6.215 8.553 11.921-1.041 5.442-6.478 9.33-11.92 8.553-5.706-.778-9.594-6.221-8.553-11.927Zm62.975 15.294c.778-4.145 4.665-7.255 8.81-6.478 4.145.778 7.255 4.666 6.478 8.811-.515 4.145-4.665 7.255-8.81 6.477-4.145-.777-7.256-4.665-6.478-8.81Z" fill="url(#c)"/><defs><radialGradient id="b" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(0 32.7063 -69.3245 0 264.232 124.706)"><stop stop-color="#047857"/><stop offset="1" stop-color="#064E3B"/></radialGradient><radialGradient id="c" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(255.837 186.754) scale(1389.61)"><stop stop-color="#047857"/><stop offset=".115" stop-color="#064E3B"/></radialGradient><linearGradient id="a" x1="224.998" y1="157.606" x2="224.998" y2="403.696" gradientUnits="userSpaceOnUse"><stop stop-color="#86EFAC" stop-opacity=".75"/><stop offset=".635" stop-color="#fff" stop-opacity=".2"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient></defs></svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -5,7 +5,7 @@
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
export {}
|
||||
|
||||
declare module 'vue' {
|
||||
declare module "vue" {
|
||||
export interface GlobalComponents {
|
||||
AppActionHandler: typeof import('./components/app/ActionHandler.vue')['default']
|
||||
AppAnnouncement: typeof import('./components/app/Announcement.vue')['default']
|
||||
@@ -59,8 +59,6 @@ declare module 'vue' {
|
||||
CollectionsRequest: typeof import('./components/collections/Request.vue')['default']
|
||||
CollectionsSaveRequest: typeof import('./components/collections/SaveRequest.vue')['default']
|
||||
CollectionsTeamCollections: typeof import('./components/collections/TeamCollections.vue')['default']
|
||||
CookiesAllModal: typeof import('./components/cookies/AllModal.vue')['default']
|
||||
CookiesEditCookie: typeof import('./components/cookies/EditCookie.vue')['default']
|
||||
Environments: typeof import('./components/environments/index.vue')['default']
|
||||
EnvironmentsAdd: typeof import('./components/environments/Add.vue')['default']
|
||||
EnvironmentsImportExport: typeof import('./components/environments/ImportExport.vue')['default']
|
||||
@@ -160,7 +158,7 @@ declare module 'vue' {
|
||||
IconLucideRss: typeof import('~icons/lucide/rss')['default']
|
||||
IconLucideSearch: typeof import('~icons/lucide/search')['default']
|
||||
IconLucideUsers: typeof import('~icons/lucide/users')['default']
|
||||
InterceptorsErrorPlaceholder: typeof import('./components/interceptors/ErrorPlaceholder.vue')['default']
|
||||
IconLucideVerified: typeof import('~icons/lucide/verified')['default']
|
||||
InterceptorsExtensionSubtitle: typeof import('./components/interceptors/ExtensionSubtitle.vue')['default']
|
||||
LensesHeadersRenderer: typeof import('./components/lenses/HeadersRenderer.vue')['default']
|
||||
LensesHeadersRendererEntry: typeof import('./components/lenses/HeadersRendererEntry.vue')['default']
|
||||
@@ -206,7 +204,6 @@ declare module 'vue' {
|
||||
SmartSlideOver: typeof import('./../../hoppscotch-ui/src/components/smart/SlideOver.vue')['default']
|
||||
SmartSpinner: typeof import('./../../hoppscotch-ui/src/components/smart/Spinner.vue')['default']
|
||||
SmartTab: typeof import('./../../hoppscotch-ui/src/components/smart/Tab.vue')['default']
|
||||
SmartTable: typeof import('./../../hoppscotch-ui/src/components/smart/Table.vue')['default']
|
||||
SmartTabs: typeof import('./../../hoppscotch-ui/src/components/smart/Tabs.vue')['default']
|
||||
SmartToggle: typeof import('./../../hoppscotch-ui/src/components/smart/Toggle.vue')['default']
|
||||
SmartTree: typeof import('./../../hoppscotch-ui/src/components/smart/Tree.vue')['default']
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
|
||||
<span class="text-white">
|
||||
<span v-if="banner.alternateText" class="md:hidden">
|
||||
{{ banner.alternateText(t) }}
|
||||
{{ banner.alternateText }}
|
||||
</span>
|
||||
<span :class="banner.alternateText ? '<md:hidden' : ''">
|
||||
{{ banner.text(t) }}
|
||||
<span class="<md:hidden">
|
||||
{{ banner.text }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
@@ -19,8 +19,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue"
|
||||
|
||||
import { BannerContent, BannerType } from "~/services/banner.service"
|
||||
import { useI18n } from "@composables/i18n"
|
||||
|
||||
import IconAlertCircle from "~icons/lucide/alert-circle"
|
||||
import IconAlertTriangle from "~icons/lucide/alert-triangle"
|
||||
@@ -30,8 +30,6 @@ const props = defineProps<{
|
||||
banner: BannerContent
|
||||
}>()
|
||||
|
||||
const t = useI18n()
|
||||
|
||||
const ariaRoles: Record<BannerType, string> = {
|
||||
error: "alert",
|
||||
warning: "status",
|
||||
|
||||
@@ -20,12 +20,6 @@
|
||||
<AppInterceptor />
|
||||
</template>
|
||||
</tippy>
|
||||
<HoppButtonSecondary
|
||||
v-if="platform.platformFeatureFlags.cookiesEnabled ?? false"
|
||||
:label="t('app.cookies')"
|
||||
:icon="IconCookie"
|
||||
@click="showCookiesModal = true"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex">
|
||||
<tippy
|
||||
@@ -201,17 +195,12 @@
|
||||
:show="showDeveloperOptions"
|
||||
@hide-modal="showDeveloperOptions = false"
|
||||
/>
|
||||
<CookiesAllModal
|
||||
:show="showCookiesModal"
|
||||
@hide-modal="showCookiesModal = false"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue"
|
||||
import { version } from "~/../package.json"
|
||||
import IconCookie from "~icons/lucide/cookie"
|
||||
import IconSidebar from "~icons/lucide/sidebar"
|
||||
import IconZap from "~icons/lucide/zap"
|
||||
import IconShare2 from "~icons/lucide/share-2"
|
||||
@@ -234,9 +223,7 @@ import { invokeAction } from "@helpers/actions"
|
||||
import { HoppSmartItem } from "@hoppscotch/ui"
|
||||
|
||||
const t = useI18n()
|
||||
|
||||
const showDeveloperOptions = ref(false)
|
||||
const showCookiesModal = ref(false)
|
||||
|
||||
const EXPAND_NAVIGATION = useSetting("EXPAND_NAVIGATION")
|
||||
const SIDEBAR = useSetting("SIDEBAR")
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
<template>
|
||||
<div>
|
||||
<header
|
||||
ref="headerRef"
|
||||
class="flex flex-1 flex-shrink-0 items-center justify-between space-x-2 overflow-x-auto overflow-y-hidden px-2 py-2"
|
||||
@mousedown.prevent="platform.ui?.appHeader?.onHeaderAreaClick?.()"
|
||||
>
|
||||
<div
|
||||
class="inline-flex flex-1 items-center justify-start space-x-2"
|
||||
@@ -217,7 +215,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<AppBanner v-if="bannerContent" :banner="bannerContent" />
|
||||
<AppBanner v-if="banner" :banner="banner" />
|
||||
<TeamsModal :show="showTeamsModal" @hide-modal="showTeamsModal = false" />
|
||||
<TeamsInvite
|
||||
v-if="workspace.type === 'team' && workspace.teamID"
|
||||
@@ -266,11 +264,7 @@ import IconUsers from "~icons/lucide/users"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import * as TE from "fp-ts/TaskEither"
|
||||
import { deleteTeam as backendDeleteTeam } from "~/helpers/backend/mutations/Team"
|
||||
import {
|
||||
BannerService,
|
||||
BannerContent,
|
||||
BANNER_PRIORITY_HIGH,
|
||||
} from "~/services/banner.service"
|
||||
import { BannerService } from "~/services/banner.service"
|
||||
|
||||
const t = useI18n()
|
||||
const toast = useToast()
|
||||
@@ -288,29 +282,18 @@ const showTeamsModal = ref(false)
|
||||
const breakpoints = useBreakpoints(breakpointsTailwind)
|
||||
const mdAndLarger = breakpoints.greater("md")
|
||||
|
||||
const banner = useService(BannerService)
|
||||
const bannerContent = computed(() => banner.content.value?.content)
|
||||
let bannerID: number | null = null
|
||||
|
||||
const offlineBanner: BannerContent = {
|
||||
type: "info",
|
||||
text: (t) => t("helpers.offline"),
|
||||
alternateText: (t) => t("helpers.offline_short"),
|
||||
score: BANNER_PRIORITY_HIGH,
|
||||
}
|
||||
|
||||
const { content: banner } = useService(BannerService)
|
||||
const network = reactive(useNetwork())
|
||||
const isOnline = computed(() => network.isOnline)
|
||||
|
||||
// Show the offline banner if the user is offline
|
||||
watch(isOnline, () => {
|
||||
if (!isOnline.value) {
|
||||
bannerID = banner.showBanner(offlineBanner)
|
||||
watch(network, () => {
|
||||
if (network.isOnline) {
|
||||
banner.value = null
|
||||
return
|
||||
} else {
|
||||
if (banner.content && bannerID) {
|
||||
banner.removeBanner(bannerID)
|
||||
}
|
||||
}
|
||||
banner.value = {
|
||||
type: "info",
|
||||
text: t("helpers.offline"),
|
||||
alternateText: t("helpers.offline_short"),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -47,15 +47,14 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Pane, Splitpanes } from "splitpanes"
|
||||
import { Splitpanes, Pane } from "splitpanes"
|
||||
|
||||
import "splitpanes/dist/splitpanes.css"
|
||||
|
||||
import { useSetting } from "@composables/settings"
|
||||
import { breakpointsTailwind, useBreakpoints } from "@vueuse/core"
|
||||
import { useService } from "dioc/vue"
|
||||
import { computed, ref, useSlots } from "vue"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
import { computed, useSlots, ref } from "vue"
|
||||
import { useSetting } from "@composables/settings"
|
||||
import { setLocalConfig, getLocalConfig } from "~/newstore/localpersistence"
|
||||
|
||||
const SIDEBAR_ON_LEFT = useSetting("SIDEBAR_ON_LEFT")
|
||||
|
||||
@@ -68,8 +67,6 @@ const SIDEBAR = useSetting("SIDEBAR")
|
||||
|
||||
const slots = useSlots()
|
||||
|
||||
const persistenceService = useService(PersistenceService)
|
||||
|
||||
const hasSidebar = computed(() => !!slots.sidebar)
|
||||
const hasSecondary = computed(() => !!slots.secondary)
|
||||
|
||||
@@ -99,7 +96,7 @@ if (!COLUMN_LAYOUT.value) {
|
||||
function setPaneEvent(event: PaneEvent[], type: "vertical" | "horizontal") {
|
||||
if (!props.layoutId) return
|
||||
const storageKey = `${props.layoutId}-pane-config-${type}`
|
||||
persistenceService.setLocalConfig(storageKey, JSON.stringify(event))
|
||||
setLocalConfig(storageKey, JSON.stringify(event))
|
||||
}
|
||||
|
||||
function populatePaneEvent() {
|
||||
@@ -122,7 +119,7 @@ function populatePaneEvent() {
|
||||
|
||||
function getPaneData(type: "vertical" | "horizontal"): PaneEvent[] | null {
|
||||
const storageKey = `${props.layoutId}-pane-config-${type}`
|
||||
const paneEvent = persistenceService.getLocalConfig(storageKey)
|
||||
const paneEvent = getLocalConfig(storageKey)
|
||||
if (!paneEvent) return null
|
||||
return JSON.parse(paneEvent)
|
||||
}
|
||||
|
||||
@@ -258,7 +258,7 @@ const importFromJSON = () => {
|
||||
inputChooseFileToImportFrom.value.value = ""
|
||||
}
|
||||
|
||||
const exportJSON = async () => {
|
||||
const exportJSON = () => {
|
||||
const dataToWrite = collectionJson.value
|
||||
|
||||
const parsedCollections = JSON.parse(dataToWrite)
|
||||
@@ -268,32 +268,24 @@ const exportJSON = async () => {
|
||||
}
|
||||
|
||||
const file = new Blob([dataToWrite], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
a.href = url
|
||||
|
||||
const filename = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: "application/json",
|
||||
suggestedFilename: filename,
|
||||
filters: [
|
||||
{
|
||||
name: "Hoppscotch Collection JSON file",
|
||||
extensions: ["json"],
|
||||
},
|
||||
],
|
||||
platform?.analytics?.logEvent({
|
||||
type: "HOPP_EXPORT_COLLECTION",
|
||||
exporter: "json",
|
||||
platform: "gql",
|
||||
})
|
||||
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
platform?.analytics?.logEvent({
|
||||
type: "HOPP_EXPORT_COLLECTION",
|
||||
exporter: "json",
|
||||
platform: "gql",
|
||||
})
|
||||
|
||||
toast.success(t("state.download_started").toString())
|
||||
}
|
||||
// TODO: get uri from meta
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
toast.success(t("state.download_started").toString())
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1866,25 +1866,28 @@ const getJSONCollection = async () => {
|
||||
* @param collectionJSON - JSON string of the collection
|
||||
* @param name - Name of the collection set as the file name
|
||||
*/
|
||||
const initializeDownloadCollection = async (
|
||||
const initializeDownloadCollection = (
|
||||
collectionJSON: string,
|
||||
name: string | null
|
||||
) => {
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: collectionJSON,
|
||||
contentType: "application/json",
|
||||
suggestedFilename: `${name ?? "collection"}.json`,
|
||||
filters: [
|
||||
{
|
||||
name: "Hoppscotch Collection JSON file",
|
||||
extensions: ["json"],
|
||||
},
|
||||
],
|
||||
})
|
||||
const file = new Blob([collectionJSON], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
a.href = url
|
||||
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
toast.success(t("state.download_started").toString())
|
||||
if (name) {
|
||||
a.download = `${name}.json`
|
||||
} else {
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
}
|
||||
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
toast.success(t("state.download_started").toString())
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1913,14 +1916,11 @@ const exportData = async (
|
||||
exportLoading.value = false
|
||||
return
|
||||
},
|
||||
async (coll) => {
|
||||
(coll) => {
|
||||
const hoppColl = teamCollToHoppRESTColl(coll)
|
||||
const collectionJSONString = JSON.stringify(hoppColl)
|
||||
|
||||
await initializeDownloadCollection(
|
||||
collectionJSONString,
|
||||
hoppColl.name
|
||||
)
|
||||
initializeDownloadCollection(collectionJSONString, hoppColl.name)
|
||||
exportLoading.value = false
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
<template>
|
||||
<HoppSmartModal
|
||||
v-if="show"
|
||||
dialog
|
||||
:title="t('app.cookies')"
|
||||
aria-modal="true"
|
||||
@close="hideModal"
|
||||
>
|
||||
<template #body>
|
||||
<HoppSmartPlaceholder
|
||||
v-if="!currentInterceptorSupportsCookies"
|
||||
:text="t('cookies.modal.interceptor_no_support')"
|
||||
>
|
||||
<AppInterceptor class="rounded border border-dividerLight p-2" />
|
||||
</HoppSmartPlaceholder>
|
||||
<div v-else class="flex flex-col">
|
||||
<div
|
||||
class="sticky -mx-4 -mt-4 flex space-x-2 border-b border-dividerLight bg-primary px-4 py-4"
|
||||
style="top: calc(-1 * var(--line-height-body))"
|
||||
>
|
||||
<HoppSmartInput
|
||||
v-model="newDomainText"
|
||||
class="flex-1"
|
||||
:placeholder="t('cookies.modal.new_domain_name')"
|
||||
@keyup.enter="addNewDomain"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
outline
|
||||
filled
|
||||
:label="t('action.add')"
|
||||
@click="addNewDomain"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col space-y-4">
|
||||
<HoppSmartPlaceholder
|
||||
v-if="workingCookieJar.size === 0"
|
||||
:src="`/images/states/${colorMode.value}/blockchain.svg`"
|
||||
:alt="`${t('cookies.modal.empty_domains')}`"
|
||||
:text="t('cookies.modal.empty_domains')"
|
||||
class="mt-6"
|
||||
>
|
||||
</HoppSmartPlaceholder>
|
||||
<div
|
||||
v-for="[domain, entries] in workingCookieJar.entries()"
|
||||
v-else
|
||||
:key="domain"
|
||||
class="flex flex-col"
|
||||
>
|
||||
<div class="flex flex-1 items-center justify-between">
|
||||
<label for="cookiesList" class="p-4">
|
||||
{{ domain }}
|
||||
</label>
|
||||
<div class="flex">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('action.delete')"
|
||||
:icon="IconTrash2"
|
||||
@click="deleteDomain(domain)"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('add.new')"
|
||||
:icon="IconPlus"
|
||||
@click="addCookieToDomain(domain)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded border border-divider">
|
||||
<div class="divide-y divide-dividerLight">
|
||||
<div
|
||||
v-if="entries.length === 0"
|
||||
class="flex flex-col items-center gap-2 p-4"
|
||||
>
|
||||
{{ t("cookies.modal.no_cookies_in_domain") }}
|
||||
</div>
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="(entry, entryIndex) in entries"
|
||||
:key="`${entry}-${entryIndex}`"
|
||||
class="flex divide-x divide-dividerLight"
|
||||
>
|
||||
<input
|
||||
class="flex flex-1 bg-transparent px-4 py-2"
|
||||
:value="entry"
|
||||
readonly
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('action.edit')"
|
||||
:icon="IconEdit"
|
||||
@click="editCookie(domain, entryIndex, entry)"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('action.remove')"
|
||||
:icon="IconTrash"
|
||||
color="red"
|
||||
@click="deleteCookie(domain, entryIndex)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="currentInterceptorSupportsCookies" #footer>
|
||||
<span class="flex space-x-2">
|
||||
<HoppButtonPrimary
|
||||
v-focus
|
||||
:label="t('action.save')"
|
||||
outline
|
||||
@click="saveCookieChanges"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
:label="t('action.cancel')"
|
||||
outline
|
||||
filled
|
||||
@click="cancelCookieChanges"
|
||||
/>
|
||||
</span>
|
||||
<HoppButtonSecondary
|
||||
:label="t('action.clear_all')"
|
||||
outline
|
||||
filled
|
||||
@click="clearAllDomains"
|
||||
/>
|
||||
</template>
|
||||
</HoppSmartModal>
|
||||
<CookiesEditCookie
|
||||
:show="!!showEditModalFor"
|
||||
:entry="showEditModalFor"
|
||||
@save-cookie="saveCookie"
|
||||
@hide-modal="showEditModalFor = null"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { useService } from "dioc/vue"
|
||||
import { CookieJarService } from "~/services/cookie-jar.service"
|
||||
import IconTrash from "~icons/lucide/trash"
|
||||
import IconEdit from "~icons/lucide/edit"
|
||||
import IconTrash2 from "~icons/lucide/trash-2"
|
||||
import IconPlus from "~icons/lucide/plus"
|
||||
import { cloneDeep } from "lodash-es"
|
||||
import { ref, watch, computed } from "vue"
|
||||
import { InterceptorService } from "~/services/interceptor.service"
|
||||
import { EditCookieConfig } from "./EditCookie.vue"
|
||||
import { useColorMode } from "@composables/theming"
|
||||
import { useToast } from "@composables/toast"
|
||||
|
||||
const props = defineProps<{
|
||||
show: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "hide-modal"): void
|
||||
}>()
|
||||
|
||||
const t = useI18n()
|
||||
const colorMode = useColorMode()
|
||||
const toast = useToast()
|
||||
|
||||
const newDomainText = ref("")
|
||||
|
||||
const interceptorService = useService(InterceptorService)
|
||||
const cookieJarService = useService(CookieJarService)
|
||||
|
||||
const workingCookieJar = ref(cloneDeep(cookieJarService.cookieJar.value))
|
||||
|
||||
const currentInterceptorSupportsCookies = computed(() => {
|
||||
const currentInterceptor = interceptorService.currentInterceptor.value
|
||||
|
||||
if (!currentInterceptor) return true
|
||||
|
||||
return currentInterceptor.supportsCookies ?? false
|
||||
})
|
||||
|
||||
function addNewDomain() {
|
||||
if (newDomainText.value === "" || /^\s+$/.test(newDomainText.value)) {
|
||||
toast.error(`${t("cookies.modal.empty_domain")}`)
|
||||
return
|
||||
}
|
||||
|
||||
workingCookieJar.value.set(newDomainText.value, [])
|
||||
newDomainText.value = ""
|
||||
}
|
||||
|
||||
function deleteDomain(domain: string) {
|
||||
workingCookieJar.value.delete(domain)
|
||||
}
|
||||
|
||||
function addCookieToDomain(domain: string) {
|
||||
showEditModalFor.value = { type: "create", domain }
|
||||
}
|
||||
|
||||
function clearAllDomains() {
|
||||
workingCookieJar.value = new Map()
|
||||
toast.success(`${t("state.cleared")}`)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
(show) => {
|
||||
if (show) {
|
||||
workingCookieJar.value = cloneDeep(cookieJarService.cookieJar.value)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const showEditModalFor = ref<EditCookieConfig | null>(null)
|
||||
|
||||
function saveCookieChanges() {
|
||||
cookieJarService.cookieJar.value = workingCookieJar.value
|
||||
hideModal()
|
||||
}
|
||||
|
||||
function cancelCookieChanges() {
|
||||
hideModal()
|
||||
}
|
||||
|
||||
function editCookie(domain: string, entryIndex: number, cookieEntry: string) {
|
||||
showEditModalFor.value = {
|
||||
type: "edit",
|
||||
domain,
|
||||
entryIndex,
|
||||
currentCookieEntry: cookieEntry,
|
||||
}
|
||||
}
|
||||
|
||||
function deleteCookie(domain: string, entryIndex: number) {
|
||||
const entry = workingCookieJar.value.get(domain)
|
||||
|
||||
if (entry) {
|
||||
entry.splice(entryIndex, 1)
|
||||
}
|
||||
}
|
||||
|
||||
function saveCookie(cookie: string) {
|
||||
if (showEditModalFor.value?.type === "create") {
|
||||
const { domain } = showEditModalFor.value
|
||||
|
||||
const entry = workingCookieJar.value.get(domain)!
|
||||
entry.push(cookie)
|
||||
|
||||
showEditModalFor.value = null
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (showEditModalFor.value?.type !== "edit") return
|
||||
|
||||
const { domain, entryIndex } = showEditModalFor.value!
|
||||
|
||||
const entry = workingCookieJar.value.get(domain)
|
||||
|
||||
if (entry) {
|
||||
entry[entryIndex] = cookie
|
||||
}
|
||||
|
||||
showEditModalFor.value = null
|
||||
}
|
||||
|
||||
const hideModal = () => {
|
||||
emit("hide-modal")
|
||||
}
|
||||
</script>
|
||||
@@ -1,195 +0,0 @@
|
||||
<template>
|
||||
<HoppSmartModal
|
||||
v-if="show"
|
||||
dialog
|
||||
:title="t('cookies.modal.set')"
|
||||
@close="hideModal"
|
||||
>
|
||||
<template #body>
|
||||
<div class="rounded border border-dividerLight">
|
||||
<div class="flex flex-col">
|
||||
<div class="flex items-center justify-between pl-4">
|
||||
<label class="truncate font-semibold text-secondaryLight">
|
||||
{{ t("cookies.modal.cookie_string") }}
|
||||
</label>
|
||||
<div class="flex items-center">
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('action.clear_all')"
|
||||
:icon="IconTrash2"
|
||||
@click="clearContent()"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:title="t('state.linewrap')"
|
||||
:class="{ '!text-accent': linewrapEnabled }"
|
||||
:icon="IconWrapText"
|
||||
@click.prevent="linewrapEnabled = !linewrapEnabled"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip', allowHTML: true }"
|
||||
:title="t('action.download_file')"
|
||||
:icon="downloadIcon"
|
||||
@click="downloadResponse"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip', allowHTML: true }"
|
||||
:title="t('action.copy')"
|
||||
:icon="copyIcon"
|
||||
@click="copyResponse"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-46">
|
||||
<div
|
||||
ref="cookieEditor"
|
||||
class="h-full rounded-b border-t border-dividerLight"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<div class="flex space-x-2">
|
||||
<HoppButtonPrimary
|
||||
v-focus
|
||||
:label="t('action.save')"
|
||||
outline
|
||||
@click="saveCookieChange"
|
||||
/>
|
||||
<HoppButtonSecondary
|
||||
:label="t('action.cancel')"
|
||||
outline
|
||||
filled
|
||||
@click="cancelCookieChange"
|
||||
/>
|
||||
</div>
|
||||
<span class="flex">
|
||||
<HoppButtonSecondary
|
||||
:icon="pasteIcon"
|
||||
:label="`${t('action.paste')}`"
|
||||
filled
|
||||
outline
|
||||
@click="handlePaste"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
</HoppSmartModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
export type EditCookieConfig =
|
||||
| { type: "create"; domain: string }
|
||||
| {
|
||||
type: "edit"
|
||||
domain: string
|
||||
entryIndex: number
|
||||
currentCookieEntry: string
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { useCodemirror } from "~/composables/codemirror"
|
||||
import { watch, ref, reactive } from "vue"
|
||||
import { refAutoReset } from "@vueuse/core"
|
||||
import IconWrapText from "~icons/lucide/wrap-text"
|
||||
import IconClipboard from "~icons/lucide/clipboard"
|
||||
import IconCheck from "~icons/lucide/check"
|
||||
import IconTrash2 from "~icons/lucide/trash-2"
|
||||
import { useToast } from "~/composables/toast"
|
||||
import {
|
||||
useCopyResponse,
|
||||
useDownloadResponse,
|
||||
} from "~/composables/lens-actions"
|
||||
|
||||
// TODO: Build Managed Mode!
|
||||
|
||||
const props = defineProps<{
|
||||
show: boolean
|
||||
|
||||
entry: EditCookieConfig | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "save-cookie", cookie: string): void
|
||||
(e: "hide-modal"): void
|
||||
}>()
|
||||
|
||||
const t = useI18n()
|
||||
|
||||
const toast = useToast()
|
||||
|
||||
const cookieEditor = ref<HTMLElement>()
|
||||
const rawCookieString = ref("")
|
||||
const linewrapEnabled = ref(true)
|
||||
|
||||
useCodemirror(
|
||||
cookieEditor,
|
||||
rawCookieString,
|
||||
reactive({
|
||||
extendedEditorConfig: {
|
||||
mode: "text/plain",
|
||||
placeholder: `${t("cookies.modal.enter_cookie_string")}`,
|
||||
lineWrapping: linewrapEnabled,
|
||||
},
|
||||
linter: null,
|
||||
completer: null,
|
||||
environmentHighlights: false,
|
||||
})
|
||||
)
|
||||
|
||||
const pasteIcon = refAutoReset<typeof IconClipboard | typeof IconCheck>(
|
||||
IconClipboard,
|
||||
1000
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.entry,
|
||||
() => {
|
||||
if (!props.entry) return
|
||||
|
||||
if (props.entry.type === "create") {
|
||||
rawCookieString.value = ""
|
||||
return
|
||||
}
|
||||
|
||||
rawCookieString.value = props.entry.currentCookieEntry
|
||||
}
|
||||
)
|
||||
|
||||
function hideModal() {
|
||||
emit("hide-modal")
|
||||
}
|
||||
|
||||
function cancelCookieChange() {
|
||||
hideModal()
|
||||
}
|
||||
|
||||
async function handlePaste() {
|
||||
try {
|
||||
const text = await navigator.clipboard.readText()
|
||||
if (text) {
|
||||
rawCookieString.value = text
|
||||
pasteIcon.value = IconCheck
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to copy: ", e)
|
||||
toast.error(t("profile.no_permission").toString())
|
||||
}
|
||||
}
|
||||
|
||||
function saveCookieChange() {
|
||||
emit("save-cookie", rawCookieString.value)
|
||||
}
|
||||
|
||||
const { copyIcon, copyResponse } = useCopyResponse(rawCookieString)
|
||||
const { downloadIcon, downloadResponse } = useDownloadResponse(
|
||||
"",
|
||||
rawCookieString
|
||||
)
|
||||
|
||||
function clearContent() {
|
||||
rawCookieString.value = ""
|
||||
}
|
||||
</script>
|
||||
@@ -375,7 +375,7 @@ const importFromPostman = ({
|
||||
importFromHoppscotch(environments)
|
||||
}
|
||||
|
||||
const exportJSON = async () => {
|
||||
const exportJSON = () => {
|
||||
const dataToWrite = environmentJson.value
|
||||
|
||||
const parsedCollections = JSON.parse(dataToWrite)
|
||||
@@ -385,27 +385,19 @@ const exportJSON = async () => {
|
||||
}
|
||||
|
||||
const file = new Blob([dataToWrite], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
a.href = url
|
||||
|
||||
const filename = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: "application/json",
|
||||
suggestedFilename: filename,
|
||||
filters: [
|
||||
{
|
||||
name: "JSON file",
|
||||
extensions: ["json"],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
toast.success(t("state.download_started").toString())
|
||||
}
|
||||
// TODO: get uri from meta
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
toast.success(t("state.download_started").toString())
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const getErrorMessage = (err: GQLError<string>) => {
|
||||
|
||||
@@ -111,21 +111,20 @@
|
||||
<script setup lang="ts">
|
||||
import { Ref, computed, onMounted, ref } from "vue"
|
||||
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { useStreamSubscriber } from "@composables/stream"
|
||||
import { useToast } from "@composables/toast"
|
||||
import { useI18n } from "@composables/i18n"
|
||||
|
||||
import { platform } from "~/platform"
|
||||
import { setLocalConfig } from "~/newstore/localpersistence"
|
||||
|
||||
import IconEmail from "~icons/auth/email"
|
||||
import IconGithub from "~icons/auth/github"
|
||||
import IconGoogle from "~icons/auth/google"
|
||||
import IconEmail from "~icons/auth/email"
|
||||
import IconMicrosoft from "~icons/auth/microsoft"
|
||||
import IconArrowLeft from "~icons/lucide/arrow-left"
|
||||
|
||||
import { useService } from "dioc/vue"
|
||||
import { LoginItemDef } from "~/platform/auth"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
|
||||
defineProps<{
|
||||
show: boolean
|
||||
@@ -139,8 +138,6 @@ const { subscribeToStream } = useStreamSubscriber()
|
||||
const t = useI18n()
|
||||
const toast = useToast()
|
||||
|
||||
const persistenceService = useService(PersistenceService)
|
||||
|
||||
const form = {
|
||||
email: "",
|
||||
}
|
||||
@@ -263,7 +260,7 @@ const signInWithEmail = async () => {
|
||||
.signInWithEmail(form.email)
|
||||
.then(() => {
|
||||
mode.value = "email-sent"
|
||||
persistenceService.setLocalConfig("emailForSignIn", form.email)
|
||||
setLocalConfig("emailForSignIn", form.email)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
|
||||
@@ -1,34 +1,23 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="flex justify-between gap-2">
|
||||
<div
|
||||
class="field-title flex-1"
|
||||
:class="{ 'field-highlighted': isHighlighted }"
|
||||
>
|
||||
{{ fieldName }}
|
||||
<span v-if="fieldArgs.length > 0">
|
||||
(
|
||||
<span v-for="(field, index) in fieldArgs" :key="`field-${index}`">
|
||||
{{ field.name }}:
|
||||
<GraphqlTypeLink
|
||||
:gql-type="field.type"
|
||||
@jump-to-type="jumpToType"
|
||||
/>
|
||||
<span v-if="index !== fieldArgs.length - 1">, </span>
|
||||
</span>
|
||||
) </span
|
||||
>:
|
||||
<GraphqlTypeLink :gql-type="gqlField.type" @jump-to-type="jumpToType" />
|
||||
</div>
|
||||
<div v-if="gqlField.deprecationReason">
|
||||
<span
|
||||
v-tippy="{ theme: 'tomato' }"
|
||||
class="flex cursor-pointer items-center gap-2 text-xs !text-red-500 hover:!text-red-600"
|
||||
:title="gqlField.deprecationReason"
|
||||
>
|
||||
<IconAlertTriangle /> {{ t("state.deprecated") }}
|
||||
<div class="field-title" :class="{ 'field-highlighted': isHighlighted }">
|
||||
{{ fieldName }}
|
||||
<span v-if="fieldArgs.length > 0">
|
||||
(
|
||||
<span v-for="(field, index) in fieldArgs" :key="`field-${index}`">
|
||||
{{ field.name }}:
|
||||
<GraphqlTypeLink
|
||||
:gql-type="field.type"
|
||||
:jump-type-callback="jumpTypeCallback"
|
||||
/>
|
||||
<span v-if="index !== fieldArgs.length - 1">, </span>
|
||||
</span>
|
||||
</div>
|
||||
) </span
|
||||
>:
|
||||
<GraphqlTypeLink
|
||||
:gql-type="gqlField.type"
|
||||
:jump-type-callback="jumpTypeCallback"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="gqlField.description"
|
||||
@@ -36,6 +25,12 @@
|
||||
>
|
||||
{{ gqlField.description }}
|
||||
</div>
|
||||
<div
|
||||
v-if="gqlField.isDeprecated"
|
||||
class="field-deprecated my-1 inline-block rounded bg-yellow-200 px-2 py-1 text-black"
|
||||
>
|
||||
{{ t("state.deprecated") }}
|
||||
</div>
|
||||
<div v-if="fieldArgs.length > 0">
|
||||
<h5 class="my-2">Arguments:</h5>
|
||||
<div class="border-l-2 border-divider pl-4">
|
||||
@@ -44,7 +39,7 @@
|
||||
{{ field.name }}:
|
||||
<GraphqlTypeLink
|
||||
:gql-type="field.type"
|
||||
@jump-to-type="jumpToType"
|
||||
:jump-type-callback="jumpTypeCallback"
|
||||
/>
|
||||
</span>
|
||||
<div
|
||||
@@ -59,36 +54,32 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
<script>
|
||||
// TypeScript + Script Setup this :)
|
||||
import { defineComponent } from "vue"
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { GraphQLType } from "graphql"
|
||||
import { computed } from "vue"
|
||||
import IconAlertTriangle from "~icons/lucide/alert-triangle"
|
||||
|
||||
const t = useI18n()
|
||||
export default defineComponent({
|
||||
props: {
|
||||
gqlField: { type: Object, default: () => ({}) },
|
||||
jumpTypeCallback: { type: Function, default: () => ({}) },
|
||||
isHighlighted: { type: Boolean, default: false },
|
||||
},
|
||||
setup() {
|
||||
return {
|
||||
t: useI18n(),
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
fieldName() {
|
||||
return this.gqlField.name
|
||||
},
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
gqlField: any
|
||||
isHighlighted: boolean
|
||||
}>(),
|
||||
{
|
||||
gqlField: {},
|
||||
isHighlighted: false,
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "jump-to-type", type: GraphQLType): void
|
||||
}>()
|
||||
|
||||
const fieldName = computed(() => props.gqlField.name)
|
||||
|
||||
const fieldArgs = computed(() => props.gqlField.args || [])
|
||||
|
||||
const jumpToType = (type: GraphQLType) => {
|
||||
emit("jump-to-type", type)
|
||||
}
|
||||
fieldArgs() {
|
||||
return this.gqlField.args || []
|
||||
},
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -69,9 +69,9 @@
|
||||
: null,
|
||||
}"
|
||||
:icon="IconGripVertical"
|
||||
class="opacity-0"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
:class="{
|
||||
'draggable-handle cursor-grab group-hover:opacity-100':
|
||||
'draggable-handle !cursor-grab group-hover:text-secondaryLight':
|
||||
index !== workingHeaders?.length - 1,
|
||||
}"
|
||||
tabindex="-1"
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { useToast } from "@composables/toast"
|
||||
import { completePageProgress, startPageProgress } from "~/modules/loadingbar"
|
||||
import { completePageProgress, startPageProgress } from "@modules/loadingbar"
|
||||
import * as gql from "graphql"
|
||||
import { clone } from "lodash-es"
|
||||
import { computed, ref, watch } from "vue"
|
||||
@@ -63,7 +63,6 @@ import {
|
||||
GQLResponseEvent,
|
||||
runGQLOperation,
|
||||
gqlMessageEvent,
|
||||
connection,
|
||||
} from "~/helpers/graphql/connection"
|
||||
import { useService } from "dioc/vue"
|
||||
import { InterceptorService } from "~/services/interceptor.service"
|
||||
@@ -153,7 +152,13 @@ const runQuery = async (
|
||||
toast.success(t("authorization.graphql_headers"))
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(e)
|
||||
// response.value = [`${e}`]
|
||||
completePageProgress()
|
||||
toast.error(
|
||||
`${t("error.something_went_wrong")}. ${t("error.check_console_details")}`,
|
||||
{}
|
||||
)
|
||||
console.error(e)
|
||||
}
|
||||
platform.analytics?.logEvent({
|
||||
@@ -172,10 +177,7 @@ watch(
|
||||
}
|
||||
|
||||
try {
|
||||
if (
|
||||
event?.type === "response" &&
|
||||
event?.operationType !== "subscription"
|
||||
) {
|
||||
if (event?.operationType !== "subscription") {
|
||||
// response.value = [event]
|
||||
emit("update:response", [event])
|
||||
} else {
|
||||
@@ -190,26 +192,6 @@ watch(
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
() => connection,
|
||||
(newVal) => {
|
||||
if (newVal.error && newVal.state === "DISCONNECTED") {
|
||||
const response = [
|
||||
{
|
||||
type: "error",
|
||||
error: {
|
||||
message: newVal.error.message(t),
|
||||
type: newVal.error.type,
|
||||
component: newVal.error.component,
|
||||
},
|
||||
},
|
||||
]
|
||||
emit("update:response", response)
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
const hideRequestModal = () => {
|
||||
showSaveRequestModal.value = false
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
<template>
|
||||
<div class="flex flex-1 flex-col overflow-auto whitespace-nowrap">
|
||||
<div
|
||||
v-if="
|
||||
response && response.length === 1 && response[0].type === 'response'
|
||||
"
|
||||
class="flex flex-1 flex-col"
|
||||
>
|
||||
<div v-if="response?.length === 1" class="flex flex-1 flex-col">
|
||||
<div
|
||||
class="sticky top-0 z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"
|
||||
>
|
||||
@@ -40,13 +35,6 @@
|
||||
</div>
|
||||
<div ref="schemaEditor" class="flex flex-1 flex-col"></div>
|
||||
</div>
|
||||
<component
|
||||
:is="response[0].error.component"
|
||||
v-else-if="
|
||||
response && response[0].type === 'error' && response[0].error.component
|
||||
"
|
||||
class="flex-1"
|
||||
/>
|
||||
<div
|
||||
v-else-if="response && response?.length > 1"
|
||||
class="flex flex-1 flex-col"
|
||||
@@ -71,7 +59,6 @@ import { useToast } from "@composables/toast"
|
||||
import { defineActionHandler } from "~/helpers/actions"
|
||||
import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
|
||||
import { GQLResponseEvent } from "~/helpers/graphql/connection"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
const t = useI18n()
|
||||
const toast = useToast()
|
||||
@@ -86,16 +73,8 @@ const props = withDefaults(
|
||||
)
|
||||
|
||||
const responseString = computed(() => {
|
||||
const response = props.response
|
||||
if (response && response[0].type === "error") {
|
||||
return ""
|
||||
} else if (
|
||||
response &&
|
||||
response.length === 1 &&
|
||||
response[0].type === "response" &&
|
||||
response[0].data
|
||||
) {
|
||||
return JSON.stringify(JSON.parse(response[0].data), null, 2)
|
||||
if (props.response?.length === 1) {
|
||||
return JSON.stringify(JSON.parse(props.response[0].data), null, 2)
|
||||
}
|
||||
return ""
|
||||
})
|
||||
@@ -132,31 +111,21 @@ const copyResponse = (str: string) => {
|
||||
toast.success(`${t("state.copied_to_clipboard")}`)
|
||||
}
|
||||
|
||||
const downloadResponse = async (str: string) => {
|
||||
const downloadResponse = (str: string) => {
|
||||
const dataToWrite = str
|
||||
const file = new Blob([dataToWrite!], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
|
||||
const filename = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: "application/json",
|
||||
suggestedFilename: filename,
|
||||
filters: [
|
||||
{
|
||||
name: "JSON file",
|
||||
extensions: ["json"],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
downloadResponseIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
}
|
||||
a.href = url
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
downloadResponseIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
defineActionHandler(
|
||||
|
||||
@@ -58,8 +58,8 @@
|
||||
v-for="(field, index) in filteredQueryFields"
|
||||
:key="`field-${index}`"
|
||||
:gql-field="field"
|
||||
:jump-type-callback="handleJumpToType"
|
||||
class="p-4"
|
||||
@jump-to-type="handleJumpToType"
|
||||
/>
|
||||
</HoppSmartTab>
|
||||
<HoppSmartTab
|
||||
@@ -72,8 +72,8 @@
|
||||
v-for="(field, index) in filteredMutationFields"
|
||||
:key="`field-${index}`"
|
||||
:gql-field="field"
|
||||
:jump-type-callback="handleJumpToType"
|
||||
class="p-4"
|
||||
@jump-to-type="handleJumpToType"
|
||||
/>
|
||||
</HoppSmartTab>
|
||||
<HoppSmartTab
|
||||
@@ -86,8 +86,8 @@
|
||||
v-for="(field, index) in filteredSubscriptionFields"
|
||||
:key="`field-${index}`"
|
||||
:gql-field="field"
|
||||
:jump-type-callback="handleJumpToType"
|
||||
class="p-4"
|
||||
@jump-to-type="handleJumpToType"
|
||||
/>
|
||||
</HoppSmartTab>
|
||||
<HoppSmartTab
|
||||
@@ -103,7 +103,7 @@
|
||||
:gql-types="graphqlTypes"
|
||||
:is-highlighted="isGqlTypeHighlighted(type)"
|
||||
:highlighted-fields="getGqlTypeHighlightedFields(type)"
|
||||
@jump-to-type="handleJumpToType"
|
||||
:jump-type-callback="handleJumpToType"
|
||||
/>
|
||||
</HoppSmartTab>
|
||||
</HoppSmartTabs>
|
||||
@@ -202,7 +202,6 @@ import {
|
||||
schemaString,
|
||||
subscriptionFields,
|
||||
} from "~/helpers/graphql/connection"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
type NavigationTabs = "history" | "collection" | "docs" | "schema"
|
||||
type GqlTabs = "queries" | "mutations" | "subscriptions" | "types"
|
||||
@@ -373,33 +372,21 @@ useCodemirror(
|
||||
})
|
||||
)
|
||||
|
||||
const downloadSchema = async () => {
|
||||
const dataToWrite = schemaString.value
|
||||
const downloadSchema = () => {
|
||||
const dataToWrite = JSON.stringify(schemaString.value, null, 2)
|
||||
const file = new Blob([dataToWrite], { type: "application/graphql" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
|
||||
const filename = `${
|
||||
url.split("/").pop()!.split("#")[0].split("?")[0]
|
||||
}.graphql`
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: "application/graphql",
|
||||
suggestedFilename: filename,
|
||||
filters: [
|
||||
{
|
||||
name: "GraphQL Schema File",
|
||||
extensions: ["graphql"],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
downloadSchemaIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
}
|
||||
a.href = url
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.graphql`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
downloadSchemaIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const copySchema = () => {
|
||||
|
||||
@@ -49,11 +49,7 @@
|
||||
v-for="(entry, index) in log"
|
||||
:key="`entry-${index}`"
|
||||
:is-open="log.length - 1 === index"
|
||||
:entry="{
|
||||
ts: entry.type === 'response' ? entry.time : undefined,
|
||||
source: 'info',
|
||||
payload: entry.type === 'response' ? entry.data : '',
|
||||
}"
|
||||
:entry="{ ts: entry.time, source: 'info', payload: entry.data }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -7,31 +7,38 @@
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { GraphQLScalarType, GraphQLType } from "graphql"
|
||||
import { computed } from "vue"
|
||||
<script lang="ts">
|
||||
import { defineComponent } from "vue"
|
||||
import { GraphQLScalarType } from "graphql"
|
||||
|
||||
const props = defineProps<{
|
||||
gqlType: GraphQLType
|
||||
}>()
|
||||
export default defineComponent({
|
||||
props: {
|
||||
// eslint-disable-next-line vue/require-default-prop
|
||||
gqlType: null,
|
||||
// (typeName: string) => void
|
||||
// eslint-disable-next-line vue/require-default-prop
|
||||
jumpTypeCallback: Function,
|
||||
},
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "jump-to-type", type: GraphQLType): void
|
||||
}>()
|
||||
computed: {
|
||||
typeString() {
|
||||
return `${this.gqlType}`
|
||||
},
|
||||
isScalar() {
|
||||
return this.resolveRootType(this.gqlType) instanceof GraphQLScalarType
|
||||
},
|
||||
},
|
||||
|
||||
const typeString = computed(() => `${props.gqlType}`)
|
||||
const isScalar = computed(() => {
|
||||
return resolveRootType(props.gqlType) instanceof GraphQLScalarType
|
||||
methods: {
|
||||
jumpToType() {
|
||||
if (this.isScalar) return
|
||||
this.jumpTypeCallback(this.gqlType)
|
||||
},
|
||||
resolveRootType(type) {
|
||||
let t = type
|
||||
while (t.ofType != null) t = t.ofType
|
||||
return t
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
function resolveRootType(type: GraphQLType) {
|
||||
let t = type as any
|
||||
while (t.ofType != null) t = t.ofType
|
||||
return t
|
||||
}
|
||||
|
||||
function jumpToType() {
|
||||
if (isScalar.value) return
|
||||
emit("jump-to-type", props.gqlType)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -54,9 +54,9 @@
|
||||
: null,
|
||||
}"
|
||||
:icon="IconGripVertical"
|
||||
class="opacity-0"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
:class="{
|
||||
'draggable-handle cursor-grab group-hover:opacity-100':
|
||||
'draggable-handle !cursor-grab group-hover:text-secondaryLight':
|
||||
index !== workingParams?.length - 1,
|
||||
}"
|
||||
tabindex="-1"
|
||||
@@ -75,7 +75,7 @@
|
||||
"
|
||||
/>
|
||||
<div v-if="entry.isFile" class="file-chips-container">
|
||||
<div class="file-chips-wrapper space-x-1">
|
||||
<div class="file-chips-wrapper space-x-2">
|
||||
<HoppSmartFileChip
|
||||
v-for="(file, fileIndex) in entry.value"
|
||||
:key="`param-${index}-file-${fileIndex}`"
|
||||
|
||||
@@ -71,9 +71,9 @@
|
||||
: null,
|
||||
}"
|
||||
:icon="IconGripVertical"
|
||||
class="opacity-0"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
:class="{
|
||||
'draggable-handle cursor-grab group-hover:opacity-100':
|
||||
'draggable-handle !cursor-grab group-hover:text-secondaryLight':
|
||||
index !== workingHeaders?.length - 1,
|
||||
}"
|
||||
tabindex="-1"
|
||||
@@ -190,13 +190,19 @@
|
||||
:icon="masking ? IconEye : IconEyeOff"
|
||||
@click="toggleMask()"
|
||||
/>
|
||||
<div v-else class="aspect-square w-8"></div>
|
||||
<HoppButtonSecondary
|
||||
v-else
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconArrowUpRight"
|
||||
:title="t('request.go_to_authorization_tab')"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
/>
|
||||
</span>
|
||||
<span>
|
||||
<HoppButtonSecondary
|
||||
v-tippy="{ theme: 'tooltip' }"
|
||||
:icon="IconArrowUpRight"
|
||||
:title="changeTabTooltip(header.source)"
|
||||
:title="t('request.go_to_authorization_tab')"
|
||||
@click="changeTab(header.source)"
|
||||
/>
|
||||
</span>
|
||||
@@ -504,15 +510,6 @@ const mask = (header: ComputedHeader) => {
|
||||
return header.header.value
|
||||
}
|
||||
|
||||
const changeTabTooltip = (tab: ComputedHeader["source"]) => {
|
||||
switch (tab) {
|
||||
case "auth":
|
||||
return t("request.go_to_authorization_tab")
|
||||
case "body":
|
||||
return t("request.go_to_body_tab")
|
||||
}
|
||||
}
|
||||
|
||||
const changeTab = (tab: ComputedHeader["source"]) => {
|
||||
if (tab === "auth") emit("change-tab", "authorization")
|
||||
else emit("change-tab", "bodyParams")
|
||||
|
||||
@@ -43,7 +43,6 @@ import { useI18n } from "@composables/i18n"
|
||||
import { useToast } from "@composables/toast"
|
||||
import { tokenRequest } from "~/helpers/oauth"
|
||||
import { getCombinedEnvVariables } from "~/helpers/preRequest"
|
||||
import * as E from "fp-ts/Either"
|
||||
|
||||
const t = useI18n()
|
||||
const toast = useToast()
|
||||
@@ -78,15 +77,6 @@ const clientSecret = pluckRef(auth, "clientSecret" as any)
|
||||
|
||||
const scope = pluckRef(auth, "scope")
|
||||
|
||||
function translateTokenRequestError(error: string) {
|
||||
switch (error) {
|
||||
case "OIDC_DISCOVERY_FAILED":
|
||||
return t("authorization.oauth.token_generation_oidc_discovery_failed")
|
||||
default:
|
||||
return t("authorization.oauth.something_went_wrong_on_token_generation")
|
||||
}
|
||||
}
|
||||
|
||||
const handleAccessTokenRequest = async () => {
|
||||
if (
|
||||
oidcDiscoveryURL.value === "" &&
|
||||
@@ -108,11 +98,7 @@ const handleAccessTokenRequest = async () => {
|
||||
clientSecret: parseTemplateString(clientSecret.value, envVars),
|
||||
scope: parseTemplateString(scope.value, envVars),
|
||||
}
|
||||
const res = await tokenRequest(tokenReqParams)
|
||||
|
||||
if (res && E.isLeft(res)) {
|
||||
toast.error(translateTokenRequestError(res.left))
|
||||
}
|
||||
await tokenRequest(tokenReqParams)
|
||||
} catch (e) {
|
||||
toast.error(`${e}`)
|
||||
}
|
||||
|
||||
@@ -71,9 +71,9 @@
|
||||
: null,
|
||||
}"
|
||||
:icon="IconGripVertical"
|
||||
class="opacity-0"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
:class="{
|
||||
'draggable-handle cursor-grab group-hover:opacity-100':
|
||||
'draggable-handle !cursor-grab group-hover:text-secondaryLight':
|
||||
index !== workingParams?.length - 1,
|
||||
}"
|
||||
tabindex="-1"
|
||||
|
||||
@@ -350,6 +350,7 @@ const newSendRequest = async () => {
|
||||
const streamResult = await streamPromise
|
||||
|
||||
requestCancelFunc.value = cancel
|
||||
|
||||
if (E.isRight(streamResult)) {
|
||||
subscribeToStream(
|
||||
streamResult.right,
|
||||
@@ -364,20 +365,6 @@ const newSendRequest = async () => {
|
||||
loading.value = false
|
||||
},
|
||||
() => {
|
||||
// TODO: Change this any to a proper type
|
||||
const result = (streamResult.right as any).value
|
||||
if (
|
||||
result.type === "network_fail" &&
|
||||
result.error?.error === "NO_PW_EXT_HOOK"
|
||||
) {
|
||||
const errorResponse: HoppRESTResponse = {
|
||||
type: "extension_error",
|
||||
error: result.error.humanMessage.heading,
|
||||
component: result.error.component,
|
||||
req: result.req,
|
||||
}
|
||||
updateRESTResponse(errorResponse)
|
||||
}
|
||||
loading.value = false
|
||||
}
|
||||
)
|
||||
|
||||
@@ -11,12 +11,6 @@
|
||||
<HoppSmartSpinner class="my-4" />
|
||||
<span class="text-secondaryLight">{{ t("state.loading") }}</span>
|
||||
</div>
|
||||
|
||||
<component
|
||||
:is="response.component"
|
||||
v-if="response.type === 'extension_error'"
|
||||
class="flex-1"
|
||||
/>
|
||||
<HoppSmartPlaceholder
|
||||
v-if="response.type === 'network_fail'"
|
||||
:src="`/images/states/${colorMode.value}/youre_lost.svg`"
|
||||
|
||||
@@ -71,9 +71,9 @@
|
||||
: null,
|
||||
}"
|
||||
:icon="IconGripVertical"
|
||||
class="opacity-0"
|
||||
class="cursor-auto text-primary hover:text-primary"
|
||||
:class="{
|
||||
'draggable-handle cursor-grab group-hover:opacity-100':
|
||||
'draggable-handle !cursor-grab group-hover:text-secondaryLight':
|
||||
index !== workingUrlEncodedParams?.length - 1,
|
||||
}"
|
||||
tabindex="-1"
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
<template>
|
||||
<HoppSmartPlaceholder
|
||||
:src="`/images/states/${colorMode.value}/youre_lost.svg`"
|
||||
:alt="`${t('error.network_fail')}`"
|
||||
:heading="t('error.network_fail')"
|
||||
large
|
||||
>
|
||||
<div class="my-1 flex flex-col items-center text-secondaryLight">
|
||||
<span>
|
||||
{{ t("error.please_install_extension") }}
|
||||
</span>
|
||||
<span>
|
||||
{{ t("error.check_how_to_add_origin") }}
|
||||
<HoppSmartLink
|
||||
blank
|
||||
to="https://docs.hoppscotch.io/documentation/features/interceptor#browser-extension"
|
||||
class="text-accent hover:text-accentDark"
|
||||
>
|
||||
here
|
||||
</HoppSmartLink>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col space-y-2 py-4">
|
||||
<span>
|
||||
<HoppSmartItem
|
||||
to="https://chrome.google.com/webstore/detail/hoppscotch-browser-extens/amknoiejhlmhancpahfcfcfhllgkpbld"
|
||||
blank
|
||||
:icon="IconChrome"
|
||||
label="Chrome"
|
||||
:info-icon="hasChromeExtInstalled ? IconCheckCircle : null"
|
||||
:active-info-icon="hasChromeExtInstalled"
|
||||
outline
|
||||
/>
|
||||
</span>
|
||||
<span>
|
||||
<HoppSmartItem
|
||||
to="https://addons.mozilla.org/en-US/firefox/addon/hoppscotch"
|
||||
blank
|
||||
:icon="IconFirefox"
|
||||
label="Firefox"
|
||||
:info-icon="hasFirefoxExtInstalled ? IconCheckCircle : null"
|
||||
:active-info-icon="hasFirefoxExtInstalled"
|
||||
outline
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
<div class="space-y-4 py-4">
|
||||
<div class="flex items-center">
|
||||
<HoppSmartToggle
|
||||
:on="extensionEnabled"
|
||||
@change="extensionEnabled = !extensionEnabled"
|
||||
>
|
||||
{{ t("settings.extensions_use_toggle") }}
|
||||
</HoppSmartToggle>
|
||||
</div>
|
||||
</div>
|
||||
</HoppSmartPlaceholder>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import IconChrome from "~icons/brands/chrome"
|
||||
import IconFirefox from "~icons/brands/firefox"
|
||||
import IconCheckCircle from "~icons/lucide/check-circle"
|
||||
import { useI18n } from "@composables/i18n"
|
||||
import { ExtensionInterceptorService } from "~/platform/std/interceptors/extension"
|
||||
import { useService } from "dioc/vue"
|
||||
import { computed } from "vue"
|
||||
import { InterceptorService } from "~/services/interceptor.service"
|
||||
import { platform } from "~/platform"
|
||||
import { useColorMode } from "~/composables/theming"
|
||||
|
||||
const colorMode = useColorMode()
|
||||
const t = useI18n()
|
||||
|
||||
const interceptorService = useService(InterceptorService)
|
||||
const extensionService = useService(ExtensionInterceptorService)
|
||||
|
||||
const hasChromeExtInstalled = extensionService.chromeExtensionInstalled
|
||||
const hasFirefoxExtInstalled = extensionService.firefoxExtensionInstalled
|
||||
|
||||
const extensionEnabled = computed({
|
||||
get() {
|
||||
return (
|
||||
interceptorService.currentInterceptorID.value ===
|
||||
extensionService.interceptorID
|
||||
)
|
||||
},
|
||||
set(active) {
|
||||
if (active) {
|
||||
interceptorService.currentInterceptorID.value =
|
||||
extensionService.interceptorID
|
||||
} else {
|
||||
interceptorService.currentInterceptorID.value =
|
||||
platform.interceptors.default
|
||||
}
|
||||
},
|
||||
})
|
||||
</script>
|
||||
@@ -44,8 +44,6 @@ import { invokeAction } from "~/helpers/actions"
|
||||
import { useDebounceFn } from "@vueuse/core"
|
||||
// TODO: Migrate from legacy mode
|
||||
|
||||
import * as E from "fp-ts/Either"
|
||||
|
||||
type ExtendedEditorConfig = {
|
||||
mode: string
|
||||
placeholder: string
|
||||
@@ -162,21 +160,6 @@ const getLanguage = (langMime: string): Language | null => {
|
||||
return null
|
||||
}
|
||||
|
||||
const formatXML = (doc: string) => {
|
||||
try {
|
||||
const formatted = xmlFormat(doc, {
|
||||
indentation: " ",
|
||||
collapseContent: true,
|
||||
lineSeparator: "\n",
|
||||
whiteSpaceAtEndOfSelfclosingTag: true,
|
||||
})
|
||||
|
||||
return E.right(formatted)
|
||||
} catch (e) {
|
||||
return E.left(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses xml-formatter to format the XML document
|
||||
* @param doc Document to parse
|
||||
@@ -188,11 +171,14 @@ const parseDoc = (
|
||||
langMime: string
|
||||
): string | undefined => {
|
||||
if (langMime === "application/xml" && doc) {
|
||||
const xmlFormatingResult = formatXML(doc)
|
||||
if (E.isRight(xmlFormatingResult)) return xmlFormatingResult.right
|
||||
return xmlFormat(doc, {
|
||||
indentation: " ",
|
||||
collapseContent: true,
|
||||
lineSeparator: "\n",
|
||||
})
|
||||
} else {
|
||||
return doc
|
||||
}
|
||||
|
||||
return doc
|
||||
}
|
||||
|
||||
const getEditorLanguage = (
|
||||
|
||||
@@ -10,7 +10,6 @@ import { useI18n } from "./i18n"
|
||||
import { refAutoReset } from "@vueuse/core"
|
||||
import { copyToClipboard } from "@helpers/utils/clipboard"
|
||||
import { HoppRESTResponse } from "@helpers/types/HoppRESTResponse"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
export function useCopyResponse(responseBodyText: Ref<any>) {
|
||||
const toast = useToast()
|
||||
@@ -41,14 +40,15 @@ export function useDownloadResponse(
|
||||
const toast = useToast()
|
||||
const t = useI18n()
|
||||
|
||||
const downloadResponse = async () => {
|
||||
const downloadResponse = () => {
|
||||
const dataToWrite = responseBody.value
|
||||
|
||||
// Guess extension and filename
|
||||
const file = new Blob([dataToWrite], { type: contentType })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
a.href = url
|
||||
|
||||
const filename = pipe(
|
||||
// TODO: get uri from meta
|
||||
a.download = pipe(
|
||||
url,
|
||||
S.split("/"),
|
||||
RNEA.last,
|
||||
@@ -58,24 +58,15 @@ export function useDownloadResponse(
|
||||
RNEA.head
|
||||
)
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
console.log(filename)
|
||||
|
||||
// TODO: Look at the mime type and determine extension ?
|
||||
const result = await platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: contentType,
|
||||
suggestedFilename: filename,
|
||||
})
|
||||
|
||||
// Assume success if unknown as we cannot determine
|
||||
if (result.type === "unknown" || result.type === "saved") {
|
||||
downloadIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
}
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
downloadIcon.value = IconCheck
|
||||
toast.success(`${t("state.download_started")}`)
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
return {
|
||||
downloadIcon,
|
||||
downloadResponse,
|
||||
|
||||
@@ -152,14 +152,12 @@ export function useStreamSubscriber(): {
|
||||
error?: (e: any) => void,
|
||||
complete?: () => void
|
||||
) => {
|
||||
let sub: Subscription | null = null
|
||||
|
||||
sub = stream.subscribe({
|
||||
const sub = stream.subscribe({
|
||||
next,
|
||||
error,
|
||||
complete: () => {
|
||||
if (complete) complete()
|
||||
if (sub) subs.splice(subs.indexOf(sub), 1)
|
||||
subs.splice(subs.indexOf(sub), 1)
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -11,9 +11,8 @@ import {
|
||||
getIntrospectionQuery,
|
||||
printSchema,
|
||||
} from "graphql"
|
||||
import { Component, computed, reactive, ref } from "vue"
|
||||
import { computed, reactive, ref } from "vue"
|
||||
import { getService } from "~/modules/dioc"
|
||||
import { getI18n } from "~/modules/i18n"
|
||||
|
||||
import { addGraphqlHistoryEntry, makeGQLHistoryEntry } from "~/newstore/history"
|
||||
|
||||
@@ -33,23 +32,13 @@ type RunQueryOptions = {
|
||||
operationType: OperationType
|
||||
}
|
||||
|
||||
export type GQLResponseEvent =
|
||||
| {
|
||||
type: "response"
|
||||
time: number
|
||||
operationName: string | undefined
|
||||
operationType: OperationType
|
||||
data: string
|
||||
rawQuery?: RunQueryOptions
|
||||
}
|
||||
| {
|
||||
type: "error"
|
||||
error: {
|
||||
type: string
|
||||
message: string
|
||||
component?: Component
|
||||
}
|
||||
}
|
||||
export type GQLResponseEvent = {
|
||||
time: number
|
||||
operationName: string | undefined
|
||||
operationType: OperationType
|
||||
data: string
|
||||
rawQuery?: RunQueryOptions
|
||||
}
|
||||
|
||||
export type ConnectionState = "CONNECTING" | "CONNECTED" | "DISCONNECTED"
|
||||
export type SubscriptionState = "SUBSCRIBING" | "SUBSCRIBED" | "UNSUBSCRIBED"
|
||||
@@ -72,11 +61,6 @@ type Connection = {
|
||||
subscriptionState: Map<string, SubscriptionState>
|
||||
socket: WebSocket | undefined
|
||||
schema: GraphQLSchema | null
|
||||
error?: {
|
||||
type: string
|
||||
message: (t: ReturnType<typeof getI18n>) => string
|
||||
component?: Component
|
||||
} | null
|
||||
}
|
||||
|
||||
const tabs = getService(GQLTabService)
|
||||
@@ -87,7 +71,6 @@ export const connection = reactive<Connection>({
|
||||
subscriptionState: new Map<string, SubscriptionState>(),
|
||||
socket: undefined,
|
||||
schema: null,
|
||||
error: null,
|
||||
})
|
||||
|
||||
export const schema = computed(() => connection.schema)
|
||||
@@ -219,19 +202,7 @@ const getSchema = async (url: string, headers: GQLHeader[]) => {
|
||||
const res = await interceptorService.runRequest(reqOptions).response
|
||||
|
||||
if (E.isLeft(res)) {
|
||||
if (
|
||||
res.left !== "cancellation" &&
|
||||
res.left.error === "NO_PW_EXT_HOOK" &&
|
||||
res.left.humanMessage
|
||||
) {
|
||||
connection.error = {
|
||||
type: res.left.error,
|
||||
message: (t: ReturnType<typeof getI18n>) =>
|
||||
res.left.humanMessage.description(t),
|
||||
component: res.left.component,
|
||||
}
|
||||
}
|
||||
|
||||
console.error(res.left)
|
||||
throw new Error(res.left.toString())
|
||||
}
|
||||
|
||||
@@ -247,7 +218,6 @@ const getSchema = async (url: string, headers: GQLHeader[]) => {
|
||||
const schema = buildClientSchema(introspectResponse.data)
|
||||
|
||||
connection.schema = schema
|
||||
connection.error = null
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
disconnect()
|
||||
@@ -310,18 +280,7 @@ export const runGQLOperation = async (options: RunQueryOptions) => {
|
||||
const result = await interceptorService.runRequest(reqOptions).response
|
||||
|
||||
if (E.isLeft(result)) {
|
||||
if (
|
||||
result.left !== "cancellation" &&
|
||||
result.left.error === "NO_PW_EXT_HOOK" &&
|
||||
result.left.humanMessage
|
||||
) {
|
||||
connection.error = {
|
||||
type: result.left.error,
|
||||
message: (t: ReturnType<typeof getI18n>) =>
|
||||
result.left.humanMessage.description(t),
|
||||
component: result.left.component,
|
||||
}
|
||||
}
|
||||
console.error(result.left)
|
||||
throw new Error(result.left.toString())
|
||||
}
|
||||
|
||||
@@ -333,7 +292,6 @@ export const runGQLOperation = async (options: RunQueryOptions) => {
|
||||
.replace(/\0+$/, "")
|
||||
|
||||
gqlMessageEvent.value = {
|
||||
type: "response",
|
||||
time: Date.now(),
|
||||
operationName: operationName ?? "query",
|
||||
data: responseText,
|
||||
@@ -341,10 +299,6 @@ export const runGQLOperation = async (options: RunQueryOptions) => {
|
||||
operationType,
|
||||
}
|
||||
|
||||
if (connection.state !== "CONNECTED") {
|
||||
connection.state = "CONNECTED"
|
||||
}
|
||||
|
||||
addQueryToHistory(options, responseText)
|
||||
|
||||
return responseText
|
||||
@@ -398,7 +352,6 @@ export const runSubscription = (
|
||||
}
|
||||
case GQL.DATA: {
|
||||
gqlMessageEvent.value = {
|
||||
type: "response",
|
||||
time: Date.now(),
|
||||
operationName,
|
||||
data: JSON.stringify(data.payload),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Environment } from "@hoppscotch/data"
|
||||
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
|
||||
import { cloneDeep } from "lodash-es"
|
||||
import { platform } from "~/platform"
|
||||
|
||||
const getEnvironmentJson = (
|
||||
environmentObj: TeamEnvironment | Environment,
|
||||
@@ -33,24 +32,17 @@ export const exportAsJSON = (
|
||||
if (!dataToWrite) return false
|
||||
|
||||
const file = new Blob([dataToWrite], { type: "application/json" })
|
||||
const a = document.createElement("a")
|
||||
const url = URL.createObjectURL(file)
|
||||
a.href = url
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
platform.io.saveFileWithDialog({
|
||||
data: dataToWrite,
|
||||
contentType: "application/json",
|
||||
// Extracts the path from url, removes fragment identifier and query parameters if any, appends the ".json" extension, and assigns it
|
||||
suggestedFilename: `${
|
||||
url.split("/").pop()!.split("#")[0].split("?")[0]
|
||||
}.json`,
|
||||
filters: [
|
||||
{
|
||||
name: "JSON file",
|
||||
extensions: ["json"],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// Extracts the path from url, removes fragment identifier and query parameters if any, appends the ".json" extension, and assigns it
|
||||
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(a)
|
||||
window.URL.revokeObjectURL(url)
|
||||
}, 0)
|
||||
return true
|
||||
}
|
||||
|
||||
245
packages/hoppscotch-common/src/helpers/oauth.js
Normal file
@@ -0,0 +1,245 @@
|
||||
import {
|
||||
getLocalConfig,
|
||||
setLocalConfig,
|
||||
removeLocalConfig,
|
||||
} from "~/newstore/localpersistence"
|
||||
|
||||
const redirectUri = `${window.location.origin}/`
|
||||
|
||||
// GENERAL HELPER FUNCTIONS
|
||||
|
||||
/**
|
||||
* Makes a POST request and parse the response as JSON
|
||||
*
|
||||
* @param {String} url - The resource
|
||||
* @param {Object} params - Configuration options
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const sendPostRequest = async (url, params) => {
|
||||
const body = Object.keys(params)
|
||||
.map((key) => `${key}=${params[key]}`)
|
||||
.join("&")
|
||||
const options = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
},
|
||||
body,
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, options)
|
||||
const data = await response.json()
|
||||
return data
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a query string into an object
|
||||
*
|
||||
* @param {String} searchQuery - The search query params
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const parseQueryString = (searchQuery) => {
|
||||
if (searchQuery === "") {
|
||||
return {}
|
||||
}
|
||||
const segments = searchQuery.split("&").map((s) => s.split("="))
|
||||
const queryString = segments.reduce(
|
||||
(obj, el) => ({ ...obj, [el[0]]: el[1] }),
|
||||
{}
|
||||
)
|
||||
return queryString
|
||||
}
|
||||
|
||||
/**
|
||||
* Get OAuth configuration from OpenID Discovery endpoint
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const getTokenConfiguration = async (endpoint) => {
|
||||
const options = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-type": "application/json",
|
||||
},
|
||||
}
|
||||
try {
|
||||
const response = await fetch(endpoint, options)
|
||||
const config = await response.json()
|
||||
return config
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
// PKCE HELPER FUNCTIONS
|
||||
|
||||
/**
|
||||
* Generates a secure random string using the browser crypto functions
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const generateRandomString = () => {
|
||||
const array = new Uint32Array(28)
|
||||
window.crypto.getRandomValues(array)
|
||||
return Array.from(array, (dec) => `0${dec.toString(16)}`.slice(-2)).join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the SHA256 hash of the input text
|
||||
*
|
||||
* @returns {Promise<ArrayBuffer>}
|
||||
*/
|
||||
|
||||
const sha256 = (plain) => {
|
||||
const encoder = new TextEncoder()
|
||||
const data = encoder.encode(plain)
|
||||
return window.crypto.subtle.digest("SHA-256", data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the input string into Base64 format
|
||||
*
|
||||
* @param {String} str - The string to be converted
|
||||
* @returns {Promise<ArrayBuffer>}
|
||||
*/
|
||||
|
||||
const base64urlencode = (
|
||||
str // Converts the ArrayBuffer to string using Uint8 array to convert to what btoa accepts.
|
||||
) =>
|
||||
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
|
||||
// Then convert the base64 encoded to base64url encoded
|
||||
// (replace + with -, replace / with _, trim trailing =)
|
||||
btoa(String.fromCharCode.apply(null, new Uint8Array(str)))
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "")
|
||||
|
||||
/**
|
||||
* Return the base64-urlencoded sha256 hash for the PKCE challenge
|
||||
*
|
||||
* @param {String} v - The randomly generated string
|
||||
* @returns {String}
|
||||
*/
|
||||
|
||||
const pkceChallengeFromVerifier = async (v) => {
|
||||
const hashed = await sha256(v)
|
||||
return base64urlencode(hashed)
|
||||
}
|
||||
|
||||
// OAUTH REQUEST
|
||||
|
||||
/**
|
||||
* Initiates PKCE Auth Code flow when requested
|
||||
*
|
||||
* @param {Object} - The necessary params
|
||||
* @returns {Void}
|
||||
*/
|
||||
|
||||
const tokenRequest = async ({
|
||||
oidcDiscoveryUrl,
|
||||
grantType,
|
||||
authUrl,
|
||||
accessTokenUrl,
|
||||
clientId,
|
||||
clientSecret,
|
||||
scope,
|
||||
}) => {
|
||||
// Check oauth configuration
|
||||
if (oidcDiscoveryUrl !== "") {
|
||||
// eslint-disable-next-line camelcase
|
||||
const { authorization_endpoint, token_endpoint } =
|
||||
await getTokenConfiguration(oidcDiscoveryUrl)
|
||||
// eslint-disable-next-line camelcase
|
||||
authUrl = authorization_endpoint
|
||||
// eslint-disable-next-line camelcase
|
||||
accessTokenUrl = token_endpoint
|
||||
}
|
||||
// Store oauth information
|
||||
setLocalConfig("tokenEndpoint", accessTokenUrl)
|
||||
setLocalConfig("client_id", clientId)
|
||||
setLocalConfig("client_secret", clientSecret)
|
||||
|
||||
// Create and store a random state value
|
||||
const state = generateRandomString()
|
||||
setLocalConfig("pkce_state", state)
|
||||
|
||||
// Create and store a new PKCE codeVerifier (the plaintext random secret)
|
||||
const codeVerifier = generateRandomString()
|
||||
setLocalConfig("pkce_codeVerifier", codeVerifier)
|
||||
|
||||
// Hash and base64-urlencode the secret to use as the challenge
|
||||
const codeChallenge = await pkceChallengeFromVerifier(codeVerifier)
|
||||
|
||||
// Build the authorization URL
|
||||
const buildUrl = () =>
|
||||
`${authUrl + `?response_type=${grantType}`}&client_id=${encodeURIComponent(
|
||||
clientId
|
||||
)}&state=${encodeURIComponent(state)}&scope=${encodeURIComponent(
|
||||
scope
|
||||
)}&redirect_uri=${encodeURIComponent(
|
||||
redirectUri
|
||||
)}&code_challenge=${encodeURIComponent(
|
||||
codeChallenge
|
||||
)}&code_challenge_method=S256`
|
||||
|
||||
// Redirect to the authorization server
|
||||
window.location = buildUrl()
|
||||
}
|
||||
|
||||
// OAUTH REDIRECT HANDLING
|
||||
|
||||
/**
|
||||
* Handle the redirect back from the authorization server and
|
||||
* get an access token from the token endpoint
|
||||
*
|
||||
* @returns {Promise<any | void>}
|
||||
*/
|
||||
|
||||
const oauthRedirect = () => {
|
||||
let tokenResponse = ""
|
||||
const q = parseQueryString(window.location.search.substring(1))
|
||||
// Check if the server returned an error string
|
||||
if (q.error) {
|
||||
alert(`Error returned from authorization server: ${q.error}`)
|
||||
}
|
||||
// If the server returned an authorization code, attempt to exchange it for an access token
|
||||
if (q.code) {
|
||||
// Verify state matches what we set at the beginning
|
||||
if (getLocalConfig("pkce_state") !== q.state) {
|
||||
alert("Invalid state")
|
||||
Promise.reject(tokenResponse)
|
||||
} else {
|
||||
try {
|
||||
// Exchange the authorization code for an access token
|
||||
tokenResponse = sendPostRequest(getLocalConfig("tokenEndpoint"), {
|
||||
grant_type: "authorization_code",
|
||||
code: q.code,
|
||||
client_id: getLocalConfig("client_id"),
|
||||
client_secret: getLocalConfig("client_secret"),
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: getLocalConfig("pkce_codeVerifier"),
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
return Promise.reject(tokenResponse)
|
||||
}
|
||||
}
|
||||
// Clean these up since we don't need them anymore
|
||||
removeLocalConfig("pkce_state")
|
||||
removeLocalConfig("pkce_codeVerifier")
|
||||
removeLocalConfig("tokenEndpoint")
|
||||
removeLocalConfig("client_id")
|
||||
removeLocalConfig("client_secret")
|
||||
return tokenResponse
|
||||
}
|
||||
return Promise.reject(tokenResponse)
|
||||
}
|
||||
|
||||
export { tokenRequest, oauthRedirect }
|
||||
@@ -1,312 +0,0 @@
|
||||
import { getService } from "~/modules/dioc"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
|
||||
import * as E from "fp-ts/Either"
|
||||
import { z } from "zod"
|
||||
|
||||
const redirectUri = `${window.location.origin}/oauth`
|
||||
|
||||
const persistenceService = getService(PersistenceService)
|
||||
|
||||
// GENERAL HELPER FUNCTIONS
|
||||
|
||||
/**
|
||||
* Makes a POST request and parse the response as JSON
|
||||
*
|
||||
* @param {String} url - The resource
|
||||
* @param {Object} params - Configuration options
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const sendPostRequest = async (url: string, params: Record<string, string>) => {
|
||||
const body = Object.keys(params)
|
||||
.map((key) => `${key}=${params[key]}`)
|
||||
.join("&")
|
||||
const options = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
},
|
||||
body,
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, options)
|
||||
const data = await response.json()
|
||||
return E.right(data)
|
||||
} catch (e) {
|
||||
return E.left("AUTH_TOKEN_REQUEST_FAILED")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a query string into an object
|
||||
*
|
||||
* @param {String} searchQuery - The search query params
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const parseQueryString = (searchQuery: string): Record<string, string> => {
|
||||
if (searchQuery === "") {
|
||||
return {}
|
||||
}
|
||||
const segments = searchQuery.split("&").map((s) => s.split("="))
|
||||
const queryString = segments.reduce(
|
||||
(obj, el) => ({ ...obj, [el[0]]: el[1] }),
|
||||
{}
|
||||
)
|
||||
return queryString
|
||||
}
|
||||
|
||||
/**
|
||||
* Get OAuth configuration from OpenID Discovery endpoint
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const getTokenConfiguration = async (endpoint: string) => {
|
||||
const options = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-type": "application/json",
|
||||
},
|
||||
}
|
||||
try {
|
||||
const response = await fetch(endpoint, options)
|
||||
const config = await response.json()
|
||||
return E.right(config)
|
||||
} catch (e) {
|
||||
return E.left("OIDC_DISCOVERY_FAILED")
|
||||
}
|
||||
}
|
||||
|
||||
// PKCE HELPER FUNCTIONS
|
||||
|
||||
/**
|
||||
* Generates a secure random string using the browser crypto functions
|
||||
*
|
||||
* @returns {Object}
|
||||
*/
|
||||
|
||||
const generateRandomString = () => {
|
||||
const array = new Uint32Array(28)
|
||||
window.crypto.getRandomValues(array)
|
||||
return Array.from(array, (dec) => `0${dec.toString(16)}`.slice(-2)).join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the SHA256 hash of the input text
|
||||
*
|
||||
* @returns {Promise<ArrayBuffer>}
|
||||
*/
|
||||
|
||||
const sha256 = (plain: string) => {
|
||||
const encoder = new TextEncoder()
|
||||
const data = encoder.encode(plain)
|
||||
return window.crypto.subtle.digest("SHA-256", data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes the input string into Base64 format
|
||||
*
|
||||
* @param {String} str - The string to be converted
|
||||
* @returns {Promise<ArrayBuffer>}
|
||||
*/
|
||||
|
||||
const base64urlencode = (
|
||||
str: ArrayBuffer // Converts the ArrayBuffer to string using Uint8 array to convert to what btoa accepts.
|
||||
) => {
|
||||
const hashArray = Array.from(new Uint8Array(str))
|
||||
|
||||
// btoa accepts chars only within ascii 0-255 and base64 encodes them.
|
||||
// Then convert the base64 encoded to base64url encoded
|
||||
// (replace + with -, replace / with _, trim trailing =)
|
||||
return btoa(String.fromCharCode.apply(null, hashArray))
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "")
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the base64-urlencoded sha256 hash for the PKCE challenge
|
||||
*
|
||||
* @param {String} v - The randomly generated string
|
||||
* @returns {String}
|
||||
*/
|
||||
|
||||
const pkceChallengeFromVerifier = async (v: string) => {
|
||||
const hashed = await sha256(v)
|
||||
return base64urlencode(hashed)
|
||||
}
|
||||
|
||||
// OAUTH REQUEST
|
||||
|
||||
type TokenRequestParams = {
|
||||
oidcDiscoveryUrl: string
|
||||
grantType: string
|
||||
authUrl: string
|
||||
accessTokenUrl: string
|
||||
clientId: string
|
||||
clientSecret: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates PKCE Auth Code flow when requested
|
||||
*
|
||||
* @param {Object} - The necessary params
|
||||
* @returns {Void}
|
||||
*/
|
||||
|
||||
const tokenRequest = async ({
|
||||
oidcDiscoveryUrl,
|
||||
grantType,
|
||||
authUrl,
|
||||
accessTokenUrl,
|
||||
clientId,
|
||||
clientSecret,
|
||||
scope,
|
||||
}: TokenRequestParams) => {
|
||||
// Check oauth configuration
|
||||
if (oidcDiscoveryUrl !== "") {
|
||||
const res = await getTokenConfiguration(oidcDiscoveryUrl)
|
||||
|
||||
const OIDCConfigurationSchema = z.object({
|
||||
authorization_endpoint: z.string(),
|
||||
token_endpoint: z.string(),
|
||||
})
|
||||
|
||||
if (E.isLeft(res)) {
|
||||
return E.left("OIDC_DISCOVERY_FAILED" as const)
|
||||
}
|
||||
|
||||
const parsedOIDCConfiguration = OIDCConfigurationSchema.safeParse(res.right)
|
||||
|
||||
if (!parsedOIDCConfiguration.success) {
|
||||
return E.left("OIDC_DISCOVERY_FAILED" as const)
|
||||
}
|
||||
|
||||
authUrl = parsedOIDCConfiguration.data.authorization_endpoint
|
||||
accessTokenUrl = parsedOIDCConfiguration.data.token_endpoint
|
||||
}
|
||||
// Store oauth information
|
||||
persistenceService.setLocalConfig("tokenEndpoint", accessTokenUrl)
|
||||
persistenceService.setLocalConfig("client_id", clientId)
|
||||
persistenceService.setLocalConfig("client_secret", clientSecret)
|
||||
|
||||
// Create and store a random state value
|
||||
const state = generateRandomString()
|
||||
persistenceService.setLocalConfig("pkce_state", state)
|
||||
|
||||
// Create and store a new PKCE codeVerifier (the plaintext random secret)
|
||||
const codeVerifier = generateRandomString()
|
||||
persistenceService.setLocalConfig("pkce_codeVerifier", codeVerifier)
|
||||
|
||||
// Hash and base64-urlencode the secret to use as the challenge
|
||||
const codeChallenge = await pkceChallengeFromVerifier(codeVerifier)
|
||||
|
||||
// Build the authorization URL
|
||||
const buildUrl = () =>
|
||||
`${authUrl + `?response_type=${grantType}`}&client_id=${encodeURIComponent(
|
||||
clientId
|
||||
)}&state=${encodeURIComponent(state)}&scope=${encodeURIComponent(
|
||||
scope
|
||||
)}&redirect_uri=${encodeURIComponent(
|
||||
redirectUri
|
||||
)}&code_challenge=${encodeURIComponent(
|
||||
codeChallenge
|
||||
)}&code_challenge_method=S256`
|
||||
|
||||
// Redirect to the authorization server
|
||||
window.location.assign(buildUrl())
|
||||
}
|
||||
|
||||
// OAUTH REDIRECT HANDLING
|
||||
|
||||
/**
|
||||
* Handle the redirect back from the authorization server and
|
||||
* get an access token from the token endpoint
|
||||
*
|
||||
* @returns {Promise<any | void>}
|
||||
*/
|
||||
|
||||
const handleOAuthRedirect = async () => {
|
||||
const queryParams = parseQueryString(window.location.search.substring(1))
|
||||
|
||||
// Check if the server returned an error string
|
||||
if (queryParams.error) {
|
||||
return E.left("AUTH_SERVER_RETURNED_ERROR" as const)
|
||||
}
|
||||
|
||||
if (!queryParams.code) {
|
||||
return E.left("NO_AUTH_CODE" as const)
|
||||
}
|
||||
|
||||
// If the server returned an authorization code, attempt to exchange it for an access token
|
||||
// Verify state matches what we set at the beginning
|
||||
if (persistenceService.getLocalConfig("pkce_state") !== queryParams.state) {
|
||||
return E.left("INVALID_STATE" as const)
|
||||
}
|
||||
|
||||
const tokenEndpoint = persistenceService.getLocalConfig("tokenEndpoint")
|
||||
const clientID = persistenceService.getLocalConfig("client_id")
|
||||
const clientSecret = persistenceService.getLocalConfig("client_secret")
|
||||
const codeVerifier = persistenceService.getLocalConfig("pkce_codeVerifier")
|
||||
|
||||
if (!tokenEndpoint) {
|
||||
return E.left("NO_TOKEN_ENDPOINT" as const)
|
||||
}
|
||||
|
||||
if (!clientID) {
|
||||
return E.left("NO_CLIENT_ID" as const)
|
||||
}
|
||||
|
||||
if (!clientSecret) {
|
||||
return E.left("NO_CLIENT_SECRET" as const)
|
||||
}
|
||||
|
||||
if (!codeVerifier) {
|
||||
return E.left("NO_CODE_VERIFIER" as const)
|
||||
}
|
||||
|
||||
// Exchange the authorization code for an access token
|
||||
const tokenResponse: E.Either<string, any> = await sendPostRequest(
|
||||
tokenEndpoint,
|
||||
{
|
||||
grant_type: "authorization_code",
|
||||
code: queryParams.code,
|
||||
client_id: clientID,
|
||||
client_secret: clientSecret,
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: codeVerifier,
|
||||
}
|
||||
)
|
||||
|
||||
// Clean these up since we don't need them anymore
|
||||
clearPKCEState()
|
||||
|
||||
if (E.isLeft(tokenResponse)) {
|
||||
return E.left("AUTH_TOKEN_REQUEST_FAILED" as const)
|
||||
}
|
||||
|
||||
const withAccessTokenSchema = z.object({
|
||||
access_token: z.string(),
|
||||
})
|
||||
|
||||
const parsedTokenResponse = withAccessTokenSchema.safeParse(
|
||||
tokenResponse.right
|
||||
)
|
||||
|
||||
return parsedTokenResponse.success
|
||||
? E.right(parsedTokenResponse.data)
|
||||
: E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)
|
||||
}
|
||||
|
||||
const clearPKCEState = () => {
|
||||
persistenceService.removeLocalConfig("pkce_state")
|
||||
persistenceService.removeLocalConfig("pkce_codeVerifier")
|
||||
persistenceService.removeLocalConfig("tokenEndpoint")
|
||||
persistenceService.removeLocalConfig("client_id")
|
||||
persistenceService.removeLocalConfig("client_secret")
|
||||
}
|
||||
|
||||
export { tokenRequest, handleOAuthRedirect }
|
||||
@@ -1,5 +1,4 @@
|
||||
import { HoppRESTRequest } from "@hoppscotch/data"
|
||||
import { Component } from "vue"
|
||||
|
||||
export type HoppRESTResponseHeader = { key: string; value: string }
|
||||
|
||||
@@ -40,9 +39,3 @@ export type HoppRESTResponse =
|
||||
|
||||
req: HoppRESTRequest
|
||||
}
|
||||
| {
|
||||
type: "extension_error"
|
||||
error: string
|
||||
component: Component
|
||||
req: HoppRESTRequest
|
||||
}
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
import { HOPP_MODULES } from "@modules/."
|
||||
import { createApp } from "vue"
|
||||
import { PlatformDef, setPlatformDef } from "./platform"
|
||||
import { setupLocalPersistence } from "./newstore/localpersistence"
|
||||
import { performMigrations } from "./helpers/migrations"
|
||||
import { initializeApp } from "./helpers/app"
|
||||
import { initBackendGQLClient } from "./helpers/backend/GQLClient"
|
||||
import { performMigrations } from "./helpers/migrations"
|
||||
import { PlatformDef, setPlatformDef } from "./platform"
|
||||
import { HOPP_MODULES } from "@modules/."
|
||||
|
||||
import "../assets/scss/tailwind.scss"
|
||||
import "../assets/themes/themes.scss"
|
||||
import "../assets/scss/styles.scss"
|
||||
import "nprogress/nprogress.css"
|
||||
import "@fontsource-variable/inter"
|
||||
import "@fontsource-variable/material-symbols-rounded"
|
||||
import "@fontsource-variable/roboto-mono"
|
||||
import "nprogress/nprogress.css"
|
||||
import "../assets/scss/styles.scss"
|
||||
import "../assets/scss/tailwind.scss"
|
||||
import "../assets/themes/themes.scss"
|
||||
|
||||
import App from "./App.vue"
|
||||
import { getService } from "./modules/dioc"
|
||||
import { PersistenceService } from "./services/persistence"
|
||||
|
||||
export function createHoppApp(el: string | Element, platformDef: PlatformDef) {
|
||||
setPlatformDef(platformDef)
|
||||
@@ -25,15 +24,12 @@ export function createHoppApp(el: string | Element, platformDef: PlatformDef) {
|
||||
// Some basic work that needs to be done before module inits even
|
||||
initBackendGQLClient()
|
||||
initializeApp()
|
||||
setupLocalPersistence()
|
||||
performMigrations()
|
||||
|
||||
HOPP_MODULES.forEach((mod) => mod.onVueAppInit?.(app))
|
||||
platformDef.addedHoppModules?.forEach((mod) => mod.onVueAppInit?.(app))
|
||||
|
||||
// TODO: Explore possibilities of moving this invocation to the service constructor
|
||||
// `toast` was coming up as `null` in the previous attempts
|
||||
getService(PersistenceService).setupLocalPersistence()
|
||||
performMigrations()
|
||||
|
||||
app.mount(el)
|
||||
|
||||
console.info(
|
||||
|
||||
@@ -61,21 +61,18 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useSetting } from "@composables/settings"
|
||||
import { breakpointsTailwind, useBreakpoints } from "@vueuse/core"
|
||||
import { useService } from "dioc/vue"
|
||||
import { Pane, Splitpanes } from "splitpanes"
|
||||
import "splitpanes/dist/splitpanes.css"
|
||||
import { computed, onBeforeMount, onMounted, ref, watch } from "vue"
|
||||
import { breakpointsTailwind, useBreakpoints } from "@vueuse/core"
|
||||
import { Splitpanes, Pane } from "splitpanes"
|
||||
import "splitpanes/dist/splitpanes.css"
|
||||
import { RouterView, useRouter } from "vue-router"
|
||||
|
||||
import { useSetting } from "@composables/settings"
|
||||
import { defineActionHandler } from "~/helpers/actions"
|
||||
import { hookKeybindingsListener } from "~/helpers/keybindings"
|
||||
import { applySetting } from "~/newstore/settings"
|
||||
import { getLocalConfig, setLocalConfig } from "~/newstore/localpersistence"
|
||||
import { useToast } from "~/composables/toast"
|
||||
import { useI18n } from "~/composables/i18n"
|
||||
import { platform } from "~/platform"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
@@ -92,8 +89,6 @@ const mdAndLarger = breakpoints.greater("md")
|
||||
const toast = useToast()
|
||||
const t = useI18n()
|
||||
|
||||
const persistenceService = useService(PersistenceService)
|
||||
|
||||
onBeforeMount(() => {
|
||||
if (!mdAndLarger.value) {
|
||||
rightSidebar.value = false
|
||||
@@ -102,19 +97,15 @@ onBeforeMount(() => {
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
const cookiesAllowed =
|
||||
persistenceService.getLocalConfig("cookiesAllowed") === "yes"
|
||||
const platformAllowsCookiePrompts =
|
||||
platform.platformFeatureFlags.promptAsUsingCookies ?? true
|
||||
|
||||
if (!cookiesAllowed && platformAllowsCookiePrompts) {
|
||||
const cookiesAllowed = getLocalConfig("cookiesAllowed") === "yes"
|
||||
if (!cookiesAllowed) {
|
||||
toast.show(`${t("app.we_use_cookies")}`, {
|
||||
duration: 0,
|
||||
action: [
|
||||
{
|
||||
text: `${t("action.learn_more")}`,
|
||||
onClick: (_, toastObject) => {
|
||||
persistenceService.setLocalConfig("cookiesAllowed", "yes")
|
||||
setLocalConfig("cookiesAllowed", "yes")
|
||||
toastObject.goAway(0)
|
||||
window
|
||||
.open("https://docs.hoppscotch.io/support/privacy", "_blank")
|
||||
@@ -124,7 +115,7 @@ onMounted(() => {
|
||||
{
|
||||
text: `${t("action.dismiss")}`,
|
||||
onClick: (_, toastObject) => {
|
||||
persistenceService.setLocalConfig("cookiesAllowed", "yes")
|
||||
setLocalConfig("cookiesAllowed", "yes")
|
||||
toastObject.goAway(0)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import * as A from "fp-ts/Array"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import * as O from "fp-ts/Option"
|
||||
import * as R from "fp-ts/Record"
|
||||
import * as A from "fp-ts/Array"
|
||||
import * as O from "fp-ts/Option"
|
||||
import { pipe } from "fp-ts/function"
|
||||
import { createI18n, I18n, I18nOptions } from "vue-i18n"
|
||||
import { HoppModule } from "."
|
||||
|
||||
import languages from "../../languages.json"
|
||||
|
||||
import { throwError } from "~/helpers/functional/error"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
import { getService } from "./dioc"
|
||||
import { getLocalConfig, setLocalConfig } from "~/newstore/localpersistence"
|
||||
|
||||
/*
|
||||
In context of this file, we have 2 main kinds of things.
|
||||
@@ -45,8 +44,6 @@ type LanguagesDef = {
|
||||
|
||||
const FALLBACK_LANG_CODE = "en"
|
||||
|
||||
const persistenceService = getService(PersistenceService)
|
||||
|
||||
// TypeScript cannot understand dir is restricted to "ltr" or "rtl" yet, hence assertion
|
||||
export const APP_LANGUAGES: LanguagesDef[] = languages as LanguagesDef[]
|
||||
|
||||
@@ -72,7 +69,7 @@ let i18nInstance: I18n<
|
||||
const resolveCurrentLocale = () =>
|
||||
pipe(
|
||||
// Resolve from locale and make sure it is in languages
|
||||
persistenceService.getLocalConfig("locale"),
|
||||
getLocalConfig("locale"),
|
||||
O.fromNullable,
|
||||
O.filter((locale) =>
|
||||
pipe(
|
||||
@@ -121,7 +118,7 @@ export const changeAppLanguage = async (locale: string) => {
|
||||
// TODO: Look into the type issues here
|
||||
i18nInstance.global.locale.value = locale
|
||||
|
||||
persistenceService.setLocalConfig("locale", locale)
|
||||
setLocalConfig("locale", locale)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -148,7 +145,7 @@ export default <HoppModule>{
|
||||
const currentLocale = resolveCurrentLocale()
|
||||
changeAppLanguage(currentLocale)
|
||||
|
||||
persistenceService.setLocalConfig("locale", currentLocale)
|
||||
setLocalConfig("locale", currentLocale)
|
||||
},
|
||||
onBeforeRouteChange(to, _, router) {
|
||||
// Convert old locale path format to new format
|
||||
|
||||
@@ -1,26 +1,22 @@
|
||||
import { useSettingStatic } from "@composables/settings"
|
||||
import { usePreferredDark, useStorage } from "@vueuse/core"
|
||||
import { App, Ref, computed, reactive, watch } from "vue"
|
||||
|
||||
import { App, computed, reactive, Ref, watch } from "vue"
|
||||
import type { HoppBgColor } from "~/newstore/settings"
|
||||
import { PersistenceService } from "~/services/persistence"
|
||||
import { useSettingStatic } from "@composables/settings"
|
||||
import { HoppModule } from "."
|
||||
import { getService } from "./dioc"
|
||||
import { hoppLocalConfigStorage } from "~/newstore/localpersistence"
|
||||
|
||||
export type HoppColorMode = {
|
||||
preference: HoppBgColor
|
||||
value: Readonly<Exclude<HoppBgColor, "system">>
|
||||
}
|
||||
|
||||
const persistenceService = getService(PersistenceService)
|
||||
|
||||
const applyColorMode = (app: App) => {
|
||||
const [settingPref] = useSettingStatic("BG_COLOR")
|
||||
|
||||
const currentLocalPreference = useStorage<HoppBgColor>(
|
||||
"nuxt-color-mode",
|
||||
"system",
|
||||
persistenceService.hoppLocalConfigStorage,
|
||||
hoppLocalConfigStorage,
|
||||
{
|
||||
listenToStorageChanges: true,
|
||||
}
|
||||
|
||||
423
packages/hoppscotch-common/src/newstore/localpersistence.ts
Normal file
@@ -0,0 +1,423 @@
|
||||
/* eslint-disable no-restricted-globals, no-restricted-syntax */
|
||||
|
||||
import { clone, assign, isEmpty } from "lodash-es"
|
||||
import {
|
||||
translateToNewRESTCollection,
|
||||
translateToNewGQLCollection,
|
||||
Environment,
|
||||
} from "@hoppscotch/data"
|
||||
import {
|
||||
settingsStore,
|
||||
bulkApplySettings,
|
||||
getDefaultSettings,
|
||||
applySetting,
|
||||
HoppAccentColor,
|
||||
HoppBgColor,
|
||||
performSettingsDataMigrations,
|
||||
} from "./settings"
|
||||
import {
|
||||
restHistoryStore,
|
||||
graphqlHistoryStore,
|
||||
setRESTHistoryEntries,
|
||||
setGraphqlHistoryEntries,
|
||||
translateToNewRESTHistory,
|
||||
translateToNewGQLHistory,
|
||||
} from "./history"
|
||||
import {
|
||||
restCollectionStore,
|
||||
graphqlCollectionStore,
|
||||
setGraphqlCollections,
|
||||
setRESTCollections,
|
||||
} from "./collections"
|
||||
import {
|
||||
replaceEnvironments,
|
||||
environments$,
|
||||
addGlobalEnvVariable,
|
||||
setGlobalEnvVariables,
|
||||
globalEnv$,
|
||||
setSelectedEnvironmentIndex,
|
||||
selectedEnvironmentIndex$,
|
||||
} from "./environments"
|
||||
import { WSRequest$, setWSRequest } from "./WebSocketSession"
|
||||
import { SIORequest$, setSIORequest } from "./SocketIOSession"
|
||||
import { SSERequest$, setSSERequest } from "./SSESession"
|
||||
import { MQTTRequest$, setMQTTRequest } from "./MQTTSession"
|
||||
import { bulkApplyLocalState, localStateStore } from "./localstate"
|
||||
import { StorageLike, watchDebounced } from "@vueuse/core"
|
||||
import { getService } from "~/modules/dioc"
|
||||
import { RESTTabService } from "~/services/tab/rest"
|
||||
import { GQLTabService } from "~/services/tab/graphql"
|
||||
|
||||
function checkAndMigrateOldSettings() {
|
||||
if (window.localStorage.getItem("selectedEnvIndex")) {
|
||||
const index = window.localStorage.getItem("selectedEnvIndex")
|
||||
if (index) {
|
||||
if (index === "-1") {
|
||||
window.localStorage.setItem(
|
||||
"selectedEnvIndex",
|
||||
JSON.stringify({
|
||||
type: "NO_ENV_SELECTED",
|
||||
})
|
||||
)
|
||||
} else if (Number(index) >= 0) {
|
||||
window.localStorage.setItem(
|
||||
"selectedEnvIndex",
|
||||
JSON.stringify({
|
||||
type: "MY_ENV",
|
||||
index: parseInt(index),
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const vuexData = JSON.parse(window.localStorage.getItem("vuex") || "{}")
|
||||
|
||||
if (isEmpty(vuexData)) return
|
||||
|
||||
const { postwoman } = vuexData
|
||||
|
||||
if (!isEmpty(postwoman?.settings)) {
|
||||
const settingsData = assign(clone(getDefaultSettings()), postwoman.settings)
|
||||
|
||||
window.localStorage.setItem("settings", JSON.stringify(settingsData))
|
||||
|
||||
delete postwoman.settings
|
||||
window.localStorage.setItem("vuex", JSON.stringify(vuexData))
|
||||
}
|
||||
|
||||
if (postwoman?.collections) {
|
||||
window.localStorage.setItem(
|
||||
"collections",
|
||||
JSON.stringify(postwoman.collections)
|
||||
)
|
||||
|
||||
delete postwoman.collections
|
||||
window.localStorage.setItem("vuex", JSON.stringify(vuexData))
|
||||
}
|
||||
|
||||
if (postwoman?.collectionsGraphql) {
|
||||
window.localStorage.setItem(
|
||||
"collectionsGraphql",
|
||||
JSON.stringify(postwoman.collectionsGraphql)
|
||||
)
|
||||
|
||||
delete postwoman.collectionsGraphql
|
||||
window.localStorage.setItem("vuex", JSON.stringify(vuexData))
|
||||
}
|
||||
|
||||
if (postwoman?.environments) {
|
||||
window.localStorage.setItem(
|
||||
"environments",
|
||||
JSON.stringify(postwoman.environments)
|
||||
)
|
||||
|
||||
delete postwoman.environments
|
||||
window.localStorage.setItem("vuex", JSON.stringify(vuexData))
|
||||
}
|
||||
|
||||
if (window.localStorage.getItem("THEME_COLOR")) {
|
||||
const themeColor = window.localStorage.getItem("THEME_COLOR")
|
||||
applySetting("THEME_COLOR", themeColor as HoppAccentColor)
|
||||
|
||||
window.localStorage.removeItem("THEME_COLOR")
|
||||
}
|
||||
|
||||
if (window.localStorage.getItem("nuxt-color-mode")) {
|
||||
const color = window.localStorage.getItem("nuxt-color-mode") as HoppBgColor
|
||||
applySetting("BG_COLOR", color)
|
||||
|
||||
window.localStorage.removeItem("nuxt-color-mode")
|
||||
}
|
||||
}
|
||||
|
||||
function setupLocalStatePersistence() {
|
||||
const localStateData = JSON.parse(
|
||||
window.localStorage.getItem("localState") ?? "{}"
|
||||
)
|
||||
|
||||
if (localStateData) bulkApplyLocalState(localStateData)
|
||||
|
||||
localStateStore.subject$.subscribe((state) => {
|
||||
window.localStorage.setItem("localState", JSON.stringify(state))
|
||||
})
|
||||
}
|
||||
|
||||
function setupSettingsPersistence() {
|
||||
const settingsData = JSON.parse(
|
||||
window.localStorage.getItem("settings") || "{}"
|
||||
)
|
||||
|
||||
const updatedSettings = settingsData
|
||||
? performSettingsDataMigrations(settingsData)
|
||||
: settingsData
|
||||
|
||||
if (updatedSettings) {
|
||||
bulkApplySettings(updatedSettings)
|
||||
}
|
||||
|
||||
settingsStore.subject$.subscribe((settings) => {
|
||||
window.localStorage.setItem("settings", JSON.stringify(settings))
|
||||
})
|
||||
}
|
||||
|
||||
function setupHistoryPersistence() {
|
||||
const restHistoryData = JSON.parse(
|
||||
window.localStorage.getItem("history") || "[]"
|
||||
).map(translateToNewRESTHistory)
|
||||
|
||||
const graphqlHistoryData = JSON.parse(
|
||||
window.localStorage.getItem("graphqlHistory") || "[]"
|
||||
).map(translateToNewGQLHistory)
|
||||
|
||||
setRESTHistoryEntries(restHistoryData)
|
||||
setGraphqlHistoryEntries(graphqlHistoryData)
|
||||
|
||||
restHistoryStore.subject$.subscribe(({ state }) => {
|
||||
window.localStorage.setItem("history", JSON.stringify(state))
|
||||
})
|
||||
|
||||
graphqlHistoryStore.subject$.subscribe(({ state }) => {
|
||||
window.localStorage.setItem("graphqlHistory", JSON.stringify(state))
|
||||
})
|
||||
}
|
||||
|
||||
function setupCollectionsPersistence() {
|
||||
const restCollectionData = JSON.parse(
|
||||
window.localStorage.getItem("collections") || "[]"
|
||||
).map(translateToNewRESTCollection)
|
||||
|
||||
const graphqlCollectionData = JSON.parse(
|
||||
window.localStorage.getItem("collectionsGraphql") || "[]"
|
||||
).map(translateToNewGQLCollection)
|
||||
|
||||
setRESTCollections(restCollectionData)
|
||||
setGraphqlCollections(graphqlCollectionData)
|
||||
|
||||
restCollectionStore.subject$.subscribe(({ state }) => {
|
||||
window.localStorage.setItem("collections", JSON.stringify(state))
|
||||
})
|
||||
|
||||
graphqlCollectionStore.subject$.subscribe(({ state }) => {
|
||||
window.localStorage.setItem("collectionsGraphql", JSON.stringify(state))
|
||||
})
|
||||
}
|
||||
|
||||
function setupEnvironmentsPersistence() {
|
||||
const environmentsData: Environment[] = JSON.parse(
|
||||
window.localStorage.getItem("environments") || "[]"
|
||||
)
|
||||
|
||||
// Check if a global env is defined and if so move that to globals
|
||||
const globalIndex = environmentsData.findIndex(
|
||||
(x) => x.name.toLowerCase() === "globals"
|
||||
)
|
||||
|
||||
if (globalIndex !== -1) {
|
||||
const globalEnv = environmentsData[globalIndex]
|
||||
globalEnv.variables.forEach((variable) => addGlobalEnvVariable(variable))
|
||||
|
||||
// Remove global from environments
|
||||
environmentsData.splice(globalIndex, 1)
|
||||
|
||||
// Just sync the changes manually
|
||||
window.localStorage.setItem(
|
||||
"environments",
|
||||
JSON.stringify(environmentsData)
|
||||
)
|
||||
}
|
||||
|
||||
replaceEnvironments(environmentsData)
|
||||
|
||||
environments$.subscribe((envs) => {
|
||||
window.localStorage.setItem("environments", JSON.stringify(envs))
|
||||
})
|
||||
}
|
||||
|
||||
function setupSelectedEnvPersistence() {
|
||||
const selectedEnvIndex = JSON.parse(
|
||||
window.localStorage.getItem("selectedEnvIndex") ?? "null"
|
||||
)
|
||||
|
||||
// If there is a selected env index, set it to the store else set it to null
|
||||
if (selectedEnvIndex) {
|
||||
setSelectedEnvironmentIndex(selectedEnvIndex)
|
||||
} else {
|
||||
setSelectedEnvironmentIndex({
|
||||
type: "NO_ENV_SELECTED",
|
||||
})
|
||||
}
|
||||
|
||||
selectedEnvironmentIndex$.subscribe((envIndex) => {
|
||||
window.localStorage.setItem("selectedEnvIndex", JSON.stringify(envIndex))
|
||||
})
|
||||
}
|
||||
|
||||
function setupWebsocketPersistence() {
|
||||
const request = JSON.parse(
|
||||
window.localStorage.getItem("WebsocketRequest") || "null"
|
||||
)
|
||||
|
||||
setWSRequest(request)
|
||||
|
||||
WSRequest$.subscribe((req) => {
|
||||
window.localStorage.setItem("WebsocketRequest", JSON.stringify(req))
|
||||
})
|
||||
}
|
||||
|
||||
function setupSocketIOPersistence() {
|
||||
const request = JSON.parse(
|
||||
window.localStorage.getItem("SocketIORequest") || "null"
|
||||
)
|
||||
|
||||
setSIORequest(request)
|
||||
|
||||
SIORequest$.subscribe((req) => {
|
||||
window.localStorage.setItem("SocketIORequest", JSON.stringify(req))
|
||||
})
|
||||
}
|
||||
|
||||
function setupSSEPersistence() {
|
||||
const request = JSON.parse(
|
||||
window.localStorage.getItem("SSERequest") || "null"
|
||||
)
|
||||
|
||||
setSSERequest(request)
|
||||
|
||||
SSERequest$.subscribe((req) => {
|
||||
window.localStorage.setItem("SSERequest", JSON.stringify(req))
|
||||
})
|
||||
}
|
||||
|
||||
function setupMQTTPersistence() {
|
||||
const request = JSON.parse(
|
||||
window.localStorage.getItem("MQTTRequest") || "null"
|
||||
)
|
||||
|
||||
setMQTTRequest(request)
|
||||
|
||||
MQTTRequest$.subscribe((req) => {
|
||||
window.localStorage.setItem("MQTTRequest", JSON.stringify(req))
|
||||
})
|
||||
}
|
||||
|
||||
function setupGlobalEnvsPersistence() {
|
||||
const globals: Environment["variables"] = JSON.parse(
|
||||
window.localStorage.getItem("globalEnv") || "[]"
|
||||
)
|
||||
|
||||
setGlobalEnvVariables(globals)
|
||||
|
||||
globalEnv$.subscribe((vars) => {
|
||||
window.localStorage.setItem("globalEnv", JSON.stringify(vars))
|
||||
})
|
||||
}
|
||||
|
||||
// TODO: Graceful error handling ?
|
||||
export function setupRESTTabsPersistence() {
|
||||
const tabService = getService(RESTTabService)
|
||||
|
||||
try {
|
||||
const state = window.localStorage.getItem("restTabState")
|
||||
if (state) {
|
||||
const data = JSON.parse(state)
|
||||
tabService.loadTabsFromPersistedState(data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Failed parsing persisted tab state, state:`,
|
||||
window.localStorage.getItem("restTabState")
|
||||
)
|
||||
}
|
||||
|
||||
watchDebounced(
|
||||
tabService.persistableTabState,
|
||||
(state) => {
|
||||
window.localStorage.setItem("restTabState", JSON.stringify(state))
|
||||
},
|
||||
{ debounce: 500, deep: true }
|
||||
)
|
||||
}
|
||||
|
||||
function setupGQLTabsPersistence() {
|
||||
const tabService = getService(GQLTabService)
|
||||
|
||||
try {
|
||||
const state = window.localStorage.getItem("gqlTabState")
|
||||
if (state) {
|
||||
const data = JSON.parse(state)
|
||||
tabService.loadTabsFromPersistedState(data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Failed parsing persisted tab state, state:`,
|
||||
window.localStorage.getItem("gqlTabState")
|
||||
)
|
||||
}
|
||||
|
||||
watchDebounced(
|
||||
tabService.persistableTabState,
|
||||
(state) => {
|
||||
window.localStorage.setItem("gqlTabState", JSON.stringify(state))
|
||||
},
|
||||
{ debounce: 500, deep: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function setupLocalPersistence() {
|
||||
checkAndMigrateOldSettings()
|
||||
|
||||
setupLocalStatePersistence()
|
||||
setupSettingsPersistence()
|
||||
setupRESTTabsPersistence()
|
||||
|
||||
setupGQLTabsPersistence()
|
||||
|
||||
setupHistoryPersistence()
|
||||
setupCollectionsPersistence()
|
||||
setupGlobalEnvsPersistence()
|
||||
setupEnvironmentsPersistence()
|
||||
setupSelectedEnvPersistence()
|
||||
setupWebsocketPersistence()
|
||||
setupSocketIOPersistence()
|
||||
setupSSEPersistence()
|
||||
setupMQTTPersistence()
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value in LocalStorage.
|
||||
*
|
||||
* NOTE: Use LocalStorage to only store non-reactive simple data
|
||||
* For more complex data, use stores and connect it to localpersistence
|
||||
*/
|
||||
export function getLocalConfig(name: string) {
|
||||
return window.localStorage.getItem(name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a value in LocalStorage.
|
||||
*
|
||||
* NOTE: Use LocalStorage to only store non-reactive simple data
|
||||
* For more complex data, use stores and connect it to localpersistence
|
||||
*/
|
||||
export function setLocalConfig(key: string, value: string) {
|
||||
window.localStorage.setItem(key, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear config value in LocalStorage.
|
||||
* @param key Key to be cleared
|
||||
*/
|
||||
export function removeLocalConfig(key: string) {
|
||||
window.localStorage.removeItem(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage system we are using in the application.
|
||||
* NOTE: This is a placeholder for being used in app.
|
||||
* This entire redirection of localStorage is to allow for
|
||||
* not refactoring the entire app code when we refactor when
|
||||
* we are building the native (which may lack localStorage,
|
||||
* or use a custom system)
|
||||
*/
|
||||
export const hoppLocalConfigStorage: StorageLike = localStorage
|
||||
@@ -94,7 +94,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted, onBeforeUnmount } from "vue"
|
||||
import { ref, onMounted, onBeforeUnmount, onBeforeMount } from "vue"
|
||||
import { safelyExtractRESTRequest } from "@hoppscotch/data"
|
||||
import { translateExtURLParams } from "~/helpers/RESTExtURLParams"
|
||||
import { useRoute } from "vue-router"
|
||||
@@ -114,6 +114,7 @@ import {
|
||||
} from "rxjs"
|
||||
import { useToast } from "~/composables/toast"
|
||||
import { watchDebounced } from "@vueuse/core"
|
||||
import { oauthRedirect } from "~/helpers/oauth"
|
||||
import { useReadonlyStream } from "~/composables/stream"
|
||||
import {
|
||||
changeCurrentSyncStatus,
|
||||
@@ -413,6 +414,28 @@ function setupTabStateSync() {
|
||||
})
|
||||
}
|
||||
|
||||
function oAuthURL() {
|
||||
onBeforeMount(async () => {
|
||||
try {
|
||||
const tokenInfo = await oauthRedirect()
|
||||
if (
|
||||
typeof tokenInfo === "object" &&
|
||||
tokenInfo.hasOwnProperty("access_token")
|
||||
) {
|
||||
if (
|
||||
tabs.currentActiveTab.value.document.request.auth.authType ===
|
||||
"oauth-2"
|
||||
) {
|
||||
tabs.currentActiveTab.value.document.request.auth.token =
|
||||
tokenInfo.access_token
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch (_) {}
|
||||
})
|
||||
}
|
||||
|
||||
defineActionHandler("contextmenu.open", ({ position, text }) => {
|
||||
if (text) {
|
||||
contextMenu.value = {
|
||||
@@ -431,6 +454,7 @@ defineActionHandler("contextmenu.open", ({ position, text }) => {
|
||||
|
||||
setupTabStateSync()
|
||||
bindRequestToURLParams()
|
||||
oAuthURL()
|
||||
|
||||
defineActionHandler("rest.request.open", ({ doc }) => {
|
||||
tabs.createNewTab(doc)
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
<template>
|
||||
<div class="flex items-center justify-center">
|
||||
<HoppSmartSpinner />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { handleOAuthRedirect } from "~/helpers/oauth"
|
||||
import { useToast } from "~/composables/toast"
|
||||
import { useI18n } from "~/composables/i18n"
|
||||
|
||||
import * as E from "fp-ts/Either"
|
||||
import { useService } from "dioc/vue"
|
||||
import { RESTTabService } from "~/services/tab/rest"
|
||||
import { onMounted } from "vue"
|
||||
|
||||
import { useRouter } from "vue-router"
|
||||
|
||||
const t = useI18n()
|
||||
const router = useRouter()
|
||||
|
||||
const toast = useToast()
|
||||
|
||||
const tabs = useService(RESTTabService)
|
||||
|
||||
function translateOAuthRedirectError(error: string) {
|
||||
switch (error) {
|
||||
case "AUTH_SERVER_RETURNED_ERROR":
|
||||
return t("authorization.oauth.redirect_auth_server_returned_error")
|
||||
|
||||
case "NO_AUTH_CODE":
|
||||
return t("authorization.oauth.redirect_no_auth_code")
|
||||
|
||||
case "INVALID_STATE":
|
||||
return t("authorization.oauth.redirect_invalid_state")
|
||||
|
||||
case "NO_TOKEN_ENDPOINT":
|
||||
return t("authorization.oauth.redirect_no_token_endpoint")
|
||||
|
||||
case "NO_CLIENT_ID":
|
||||
return t("authorization.oauth.redirect_no_client_id")
|
||||
|
||||
case "NO_CLIENT_SECRET":
|
||||
return t("authorization.oauth.redirect_no_client_secret")
|
||||
|
||||
case "NO_CODE_VERIFIER":
|
||||
return t("authorization.oauth.redirect_no_code_verifier")
|
||||
|
||||
case "AUTH_TOKEN_REQUEST_FAILED":
|
||||
return t("authorization.oauth.redirect_auth_token_request_failed")
|
||||
|
||||
case "AUTH_TOKEN_REQUEST_INVALID_RESPONSE":
|
||||
return t(
|
||||
"authorization.oauth.redirect_auth_token_request_invalid_response"
|
||||
)
|
||||
|
||||
default:
|
||||
return t("authorization.oauth.something_went_wrong_on_oauth_redirect")
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const tokenInfo = await handleOAuthRedirect()
|
||||
|
||||
if (E.isLeft(tokenInfo)) {
|
||||
toast.error(translateOAuthRedirectError(tokenInfo.left))
|
||||
router.push("/")
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
tabs.currentActiveTab.value.document.request.auth.authType === "oauth-2"
|
||||
) {
|
||||
tabs.currentActiveTab.value.document.request.auth.token =
|
||||
tokenInfo.right.access_token
|
||||
|
||||
router.push("/")
|
||||
return
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -143,6 +143,8 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ProfileUserDelete />
|
||||
|
||||
<section class="p-4">
|
||||
<h4 class="font-semibold text-secondaryDark">
|
||||
{{ t("settings.sync") }}
|
||||
@@ -178,18 +180,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<template v-if="platform.ui?.additionalProfileSections?.length">
|
||||
<template
|
||||
v-for="item in platform.ui?.additionalProfileSections"
|
||||
:key="item.id"
|
||||
>
|
||||
<component :is="item" />
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<ProfileShortcodes />
|
||||
|
||||
<ProfileUserDelete />
|
||||
</div>
|
||||
</HoppSmartTab>
|
||||
<HoppSmartTab :id="'teams'" :label="t('team.title')">
|
||||
|
||||