Skip to content

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

feat: initial team invites implementation

Andrew Bastin9af8a24a89b6
diff --git a/packages/hoppscotch-app/components/teams/Invite.vue b/packages/hoppscotch-app/components/teams/Invite.vue
index 966aa5ee3..4f61d3e53 100644
--- a/packages/hoppscotch-app/components/teams/Invite.vue
+++ b/packages/hoppscotch-app/components/teams/Invite.vue
@@ -9,53 +9,88 @@
</div>
<div class="divide-y divide-dividerLight border-divider border rounded">
<div
- v-for="(member, index) in members"
- :key="`member-${index}`"
- class="divide-x divide-dividerLight flex"
+ v-if="pendingInvites.loading"
+ class="flex p-4 items-center justify-center"
>
- <input
- class="bg-transparent text-secondaryLight flex flex-1 py-2 px-4"
- :placeholder="$t('team.email')"
- :name="'param' + index"
- :value="member.user.email"
- readonly
- />
- <input
- class="bg-transparent text-secondaryLight flex flex-1 py-2 px-4"
- :placeholder="$t('team.permissions')"
- :name="'value' + index"
- :value="
- typeof member.role === 'string'
- ? member.role
- : JSON.stringify(member.role)
+ <SmartSpinner />
+ </div>
+ <div v-else>
+ <div
+ v-if="!pendingInvites.loading && E.isRight(pendingInvites.data)"
+ >
+ <div
+ v-for="(invitee, index) in pendingInvites.data.right.team
+ .teamInvitations"
+ :key="`invitee-${index}`"
+ class="divide-x divide-dividerLight flex"
+ >
+ <input
+ v-if="invitee"
+ class="
+ bg-transparent
+ flex flex-1
+ text-secondaryLight
+ py-2
+ px-4
+ "
+ :placeholder="`${$t('team.email')}`"
+ :name="'param' + index"
+ :value="invitee.inviteeEmail"
+ readonly
+ />
+ <input
+ class="
+ bg-transparent
+ flex flex-1
+ text-secondaryLight
+ py-2
+ px-4
+ "
+ :placeholder="`${$t('team.permissions')}`"
+ :name="'value' + index"
+ :value="
+ typeof invitee.inviteeRole === 'string'
+ ? invitee.inviteeRole
+ : JSON.stringify(invitee.inviteeRole)
+ "
+ readonly
+ />
+ <div class="flex">
+ <ButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ :title="$t('action.remove')"
+ svg="trash"
+ color="red"
+ @click.native="removeInvitee(invitee.id)"
+ />
+ </div>
+ </div>
+ </div>
+ <div
+ v-if="
+ E.isRight(pendingInvites.data) &&
+ pendingInvites.data.right.team.teamInvitations.length === 0
"
- readonly
- />
- <div class="flex">
- <ButtonSecondary
- id="member"
- v-tippy="{ theme: 'tooltip' }"
- :title="$t('action.remove')"
- svg="trash"
- color="red"
- @click.native="removeExistingTeamMember(member.user.uid)"
- />
+ class="
+ flex flex-col
+ text-secondaryLight
+ p-4
+ items-center
+ justify-center
+ "
+ >
+ <SmartIcon class="opacity-75 pb-2" name="users" />
+ <span class="text-center">
+ {{ $t("empty.pending_invites") }}
+ </span>
+ </div>
+ <div
+ v-if="!pendingInvites.loading && E.isLeft(pendingInvites.data)"
+ class="flex flex-col p-4 items-center"
+ >
+ <i class="mb-4 material-icons">help_outline</i>
+ {{ $t("error.something_went_wrong") }}
</div>
- </div>
- <div
- v-if="members.length === 0"
- class="
- flex flex-col
- text-secondaryLight
- p-4
- items-center
- justify-center
- "
- >
- <SmartIcon class="opacity-75 pb-2" name="users" />
- <span class="text-center pb-4">
- {{ $t("empty.pending_invites") }}
- </span>
</div>
</div>
<div class="flex flex-1 justify-between items-center">
@@ -66,21 +101,21 @@
<ButtonSecondary
svg="plus"
:label="$t('add.new')"
- @click.native="addTeamMember"
+ @click.native="addNewInvitee"
/>
</div>
</div>
<div class="divide-y divide-dividerLight border-divider border rounded">
<div
- v-for="(member, index) in newMembers"
- :key="`new-member-${index}`"
+ v-for="(invitee, index) in newInvites"
+ :key="`new-invitee-${index}`"
class="divide-x divide-dividerLight flex"
>
<input
- v-model="member.key"
+ v-model="invitee.key"
class="bg-transparent flex flex-1 py-2 px-4"
:placeholder="$t('team.email')"
- :name="'member' + index"
+ :name="'invitee' + index"
autofocus
/>
<span>
@@ -104,9 +139,9 @@
:placeholder="$t('team.permissions')"
:name="'value' + index"
:value="
- typeof member.value === 'string'
- ? member.value
- : JSON.stringify(member.value)
+ typeof invitee.value === 'string'
+ ? invitee.value
+ : JSON.stringify(invitee.value)
"
readonly
/>
@@ -114,15 +149,15 @@
</template>
<SmartItem
label="OWNER"
- @click.native="updateNewMemberRole(index, 'OWNER')"
+ @click.native="updateNewInviteeRole(index, 'OWNER')"
/>
<SmartItem
label="EDITOR"
- @click.native="updateNewMemberRole(index, 'EDITOR')"
+ @click.native="updateNewInviteeRole(index, 'EDITOR')"
/>
<SmartItem
label="VIEWER"
- @click.native="updateNewMemberRole(index, 'VIEWER')"
+ @click.native="updateNewInviteeRole(index, 'VIEWER')"
/>
</tippy>
</span>
@@ -133,12 +168,12 @@
:title="$t('action.remove')"
svg="trash"
color="red"
- @click.native="removeTeamMember(index)"
+ @click.native="removeNewInvitee(index)"
/>
</div>
</div>
<div
- v-if="newMembers.length === 0"
+ v-if="newInvites.length === 0"
class="
flex flex-col
text-secondaryLight
@@ -154,7 +189,7 @@
<ButtonSecondary
:label="$t('add.new')"
filled
- @click.native="addTeamMember"
+ @click.native="addNewInvitee"
/>
</div>
</div>
@@ -162,7 +197,7 @@
</template>
<template #footer>
<span>
- <ButtonPrimary :label="$t('team.invite')" @click.native="saveTeam" />
+ <ButtonPrimary :label="$t('team.invite')" @click.native="sendInvites" />
<ButtonSecondary
:label="$t('action.cancel')"
@click.native="hideModal"
@@ -172,145 +207,81 @@
</SmartModal>
</template>
-<script>
-import cloneDeep from "lodash/cloneDeep"
-import { defineComponent } from "@nuxtjs/composition-api"
-import * as teamUtils from "~/helpers/teams/utils"
-import TeamMemberAdapter from "~/helpers/teams/TeamMemberAdapter"
+<script setup lang="ts">
+import { watch, ref, reactive } from "@nuxtjs/composition-api"
+import * as E from "fp-ts/Either"
+import { useGQLQuery } from "~/helpers/backend/GQLClient"
+import {
+ GetPendingInvitesDocument,
+ GetPendingInvitesQuery,
+ GetPendingInvitesQueryVariables,
+} from "~/helpers/backend/graphql"
-export default defineComponent({
- props: {
- show: Boolean,
- editingTeam: { type: Object, default: () => {} },
- editingteamID: { type: String, default: null },
- },
- data() {
- return {
- members: [],
- newMembers: [],
- membersAdapter: new TeamMemberAdapter(null),
- }
- },
- watch: {
- editingteamID(teamID) {
- this.membersAdapter.changeTeamID(teamID)
- },
- },
- mounted() {
- this.membersAdapter.members$.subscribe((list) => {
- this.members = cloneDeep(list)
- })
- },
- methods: {
- updateMemberRole(id, role) {
- this.members[id].role = role
- this.$refs[`memberOptions-${id}`][0].tippy().hide()
- },
- updateNewMemberRole(id, role) {
- this.newMembers[id].value = role
- this.$refs[`newMemberOptions-${id}`][0].tippy().hide()
- },
- addTeamMember() {
- const member = { key: "", value: "" }
- this.newMembers.push(member)
- },
- removeExistingTeamMember(userID) {
- teamUtils
- .removeTeamMember(this.$apollo, userID, this.editingteamID)
- .then(() => {
- this.$toast.success(this.$t("team.member_removed"), {
- icon: "done",
- })
- this.hideModal()
- })
- .catch((e) => {
- this.$toast.error(this.$t("error.something_went_wrong"), {
- icon: "error_outline",
- })
- console.error(e)
- })
- },
- removeTeamMember(index) {
- this.newMembers.splice(index, 1)
- },
- validateEmail(emailID) {
- if (
- /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(
- emailID
- )
- ) {
- return true
- }
- return false
- },
- saveTeam() {
- let invalidEmail = false
- this.$data.newMembers.forEach((element) => {
- if (!this.validateEmail(element.key)) {
- this.$toast.error(this.$t("team.invalid_email_format"), {
- icon: "error_outline",
- })
- invalidEmail = true
- }
- })
- if (invalidEmail) return
- let invalidPermission = false
- this.$data.newMembers.forEach((element) => {
- if (!element.value) {
- this.$toast.error(this.$t("invalid_member_permission"), {
- icon: "error_outline",
- })
- invalidPermission = true
- }
- })
- if (invalidPermission) return
- this.$data.newMembers.forEach((element) => {
- // Call to the graphql mutation
- teamUtils
- .addTeamMemberByEmail(
- this.$apollo,
- element.value,
- element.key,
- this.editingteamID
- )
- .then(() => {
- this.$toast.success(this.$t("team.saved"), {
- icon: "done",
- })
- })
- .catch((e) => {
- this.$toast.error(e, {
- icon: "error_outline",
- })
- console.error(e)
- })
- })
- this.members.forEach((element) => {
- teamUtils
- .updateTeamMemberRole(
- this.$apollo,
- element.user.uid,
- element.role,
- this.editingteamID
- )
- .then(() => {
- this.$toast.success(this.$t("team.member_role_updated"), {
- icon: "done",
- })
- })
- .catch((e) => {
- this.$toast.error(e, {
- icon: "error_outline",
- })
- console.error(e)
- })
- })
- this.hideModal()
- },
- hideModal() {
- this.newMembers = []
- this.$emit("hide-modal")
- },
- },
+const props = defineProps({
+ show: Boolean,
+ editingteamID: { type: String, default: null },
+})
+
+const emit = defineEmits<{
+ (e: "hide-modal"): void
+}>()
+
+const pendingInvites = useGQLQuery<
+ GetPendingInvitesQuery,
+ GetPendingInvitesQueryVariables,
+ ""
+>({
+ query: GetPendingInvitesDocument,
+ variables: reactive({
+ teamID: props.editingteamID,
+ }),
+ defer: true,
})
+
+watch(
+ () => props.editingteamID,
+ () => {
+ if (props.editingteamID) {
+ pendingInvites.execute({
+ teamID: props.editingteamID,
+ })
+ }
+ }
+)
+
+watch(
+ () => pendingInvites,
+ () => {
+ console.log(pendingInvites)
+ }
+)
+
+const removeInvitee = (id: string) => {
+ console.log(id)
+}
+
+const newInvites = ref([])
+
+const addNewInvitee = () => {
+ newInvites.value.push({
+ key: "",
+ value: "",
+ })
+}
+
+const updateNewInviteeRole = (index: number, role: string) => {
+ newInvites.value[index].value = role
+}
+
+const removeNewInvitee = (id: number) => {
+ newInvites.value.splice(id, 1)
+}
+
+const sendInvites = () => {
+ console.log(newInvites.value)
+}
+
+const hideModal = () => {
+ emit("hide-modal")
+}
</script>
diff --git a/packages/hoppscotch-app/components/teams/index.vue b/packages/hoppscotch-app/components/teams/index.vue
index 76132e784..8d041fb47 100644
--- a/packages/hoppscotch-app/components/teams/index.vue
+++ b/packages/hoppscotch-app/components/teams/index.vue
@@ -49,7 +49,7 @@
</div>
<div
v-if="!myTeams.loading && E.isLeft(myTeams.data)"
- class="flex items-center flex-col"
+ class="flex flex-col items-center"
>
<i class="mb-4 material-icons">help_outline</i>
{{ $t("error.something_went_wrong") }}
@@ -65,7 +65,6 @@
"
:team="myTeams.data.right.myTeams[0]"
:show="showModalEdit"
- :editing-team="editingTeam"
:editingteam-i-d="editingTeamID"
@hide-modal="displayModalEdit(false)"
@invite-team="inviteTeam(editingTeam, editingTeamID)"
@@ -114,7 +113,9 @@ const myTeams = useGQLQuery<
MyTeamsQuery,
MyTeamsQueryVariables,
MyTeamsQueryError
->(MyTeamsDocument)
+>({
+ query: MyTeamsDocument,
+})
watchEffect(() => {
console.log(myTeams)
diff --git a/packages/hoppscotch-app/helpers/backend/GQLClient.ts b/packages/hoppscotch-app/helpers/backend/GQLClient.ts
index eee93e3ee..e1c38cf8e 100644
--- a/packages/hoppscotch-app/helpers/backend/GQLClient.ts
+++ b/packages/hoppscotch-app/helpers/backend/GQLClient.ts
@@ -1,10 +1,11 @@
import {
- computed,
ref,
- onMounted,
- onBeforeUnmount,
reactive,
Ref,
+ unref,
+ watchEffect,
+ watchSyncEffect,
+ WatchStopHandle,
} from "@nuxtjs/composition-api"
import {
createClient,
@@ -14,6 +15,8 @@ import {
OperationContext,
fetchExchange,
makeOperation,
+ GraphQLRequest,
+ createRequest,
} from "@urql/core"
import { authExchange } from "@urql/exchange-auth"
import { offlineExchange } from "@urql/exchange-graphcache"
@@ -22,8 +25,7 @@ import { devtoolsExchange } from "@urql/devtools"
import * as E from "fp-ts/Either"
import * as TE from "fp-ts/TaskEither"
import { pipe, constVoid } from "fp-ts/function"
-import { subscribe } from "wonka"
-import clone from "lodash/clone"
+import { Source, subscribe, pipe as wonkaPipe, onEnd } from "wonka"
import { keyDefs } from "./caching/keys"
import { optimisticDefs } from "./caching/optimistic"
import { updatesDef } from "./caching/updates"
@@ -45,7 +47,7 @@ const storage = makeDefaultStorage({
maxAge: 7,
})
-const client = createClient({
+export const client = createClient({
url: BACKEND_GQL_URL,
exchanges: [
devtoolsExchange,
@@ -97,6 +99,15 @@ const client = createClient({
],
})
+type MaybeRef<X> = X | Ref<X>
+
+type UseQueryOptions<T = any, V = object> = {
+ query: TypedDocumentNode<T, V>
+ variables?: MaybeRef<V>
+
+ defer?: boolean
+}
+
/**
* A wrapper type for defining errors possible in a GQL operation
*/
@@ -110,118 +121,125 @@ export type GQLError<T extends string> =
error: T
}
-const DEFAULT_QUERY_OPTIONS = {
- noPolling: false,
- pause: undefined as Ref<boolean> | undefined,
-}
+export const useGQLQuery = <DocType, DocVarType, DocErrorType extends string>(
+ _args: UseQueryOptions<DocType, DocVarType>
+) => {
+ const stops: WatchStopHandle[] = []
-type GQL_QUERY_OPTIONS = typeof DEFAULT_QUERY_OPTIONS
+ const args = reactive(_args)
-type UseQueryLoading = {
- loading: true
-}
+ const loading: Ref<boolean> = ref(true)
+ const isStale: Ref<boolean> = ref(true)
+ const data: Ref<E.Either<GQLError<DocErrorType>, DocType>> = ref() as any
-type UseQueryLoaded<
- QueryFailType extends string = "",
- QueryReturnType = any
-> = {
- loading: false
- data: E.Either<GQLError<QueryFailType>, QueryReturnType>
-}
-
-type UseQueryReturn<QueryFailType extends string = "", QueryReturnType = any> =
- | UseQueryLoading
- | UseQueryLoaded<QueryFailType, QueryReturnType>
+ const isPaused: Ref<boolean> = ref(args.defer ?? false)
-export function isLoadedGQLQuery<QueryFailType extends string, QueryReturnType>(
- x: UseQueryReturn<QueryFailType, QueryReturnType>
-): x is {
- loading: false
- data: E.Either<GQLError<QueryFailType>, QueryReturnType>
-} {
- return !x.loading
-}
+ const request: Ref<GraphQLRequest<DocType, DocVarType>> = ref(
+ createRequest<DocType, DocVarType>(
+ args.query,
+ unref<DocVarType>(args.variables as any) as any
+ )
+ ) as any
-export function useGQLQuery<
- QueryReturnType = any,
- QueryVariables extends object = {},
- QueryFailType extends string = ""
->(
- query: TypedDocumentNode<QueryReturnType, QueryVariables>,
- variables?: QueryVariables,
- options: Partial<GQL_QUERY_OPTIONS> = DEFAULT_QUERY_OPTIONS
-):
- | { loading: false; data: E.Either<GQLError<QueryFailType>, QueryReturnType> }
- | { loading: true } {
- type DataType = E.Either<GQLError<QueryFailType>, QueryReturnType>
+ const source: Ref<Source<OperationResult> | undefined> = ref()
- const finalOptions = Object.assign(clone(DEFAULT_QUERY_OPTIONS), options)
+ stops.push(
+ watchEffect(
+ () => {
+ const newRequest = createRequest<DocType, DocVarType>(
+ args.query,
+ unref<DocVarType>(args.variables as any) as any
+ )
- const data = ref<DataType>()
+ if (request.value.key !== newRequest.key) {
+ request.value = newRequest
+ }
+ },
+ { flush: "pre" }
+ )
+ )
- let subscription: { unsubscribe(): void } | null = null
+ stops.push(
+ watchEffect(
+ () => {
+ source.value = !isPaused.value
+ ? client.executeQuery<DocType, DocVarType>(request.value, {
+ requestPolicy: "cache-and-network",
+ })
+ : undefined
+ },
+ { flush: "pre" }
+ )
+ )
- onMounted(() => {
- const gqlQuery = client.query<any, QueryVariables>(query, variables, {
- requestPolicy: "cache-and-network",
- })
+ watchSyncEffect((onInvalidate) => {
+ if (source.value) {
+ loading.value = true
+ isStale.value = false
- const processResult = (result: OperationResult<any, QueryVariables>) =>
- pipe(
- // The target
- result.data as QueryReturnType | undefined,
- // Define what happens if data does not exist (it is an error)
- E.fromNullable(
- pipe(
- // Take the network error value
- result.error?.networkError,
- // If it null, set the left to the generic error name
- E.fromNullable(result.error?.message),
- E.match(
- // The left case (network error was null)
- (gqlErr) =>
- <GQLError<QueryFailType>>{
- type: "gql_error",
- error: gqlErr as QueryFailType,
- },
- // The right case (it was a GraphQL Error)
- (networkErr) =>
- <GQLError<QueryFailType>>{
- type: "network_error",
- error: networkErr,
- }
+ onInvalidate(
+ wonkaPipe(
+ source.value,
+ onEnd(() => {
+ loading.value = false
+ isStale.value = false
+ }),
+ subscribe((res) => {
+ data.value = pipe(
+ // The target
+ res.data as DocType | undefined,
+ // Define what happens if data does not exist (it is an error)
+ E.fromNullable(
+ pipe(
+ // Take the network error value
+ res.error?.networkError,
+ // If it null, set the left to the generic error name
+ E.fromNullable(res.error?.message),
+ E.match(
+ // The left case (network error was null)
+ (gqlErr) =>
+ <GQLError<DocErrorType>>{
+ type: "gql_error",
+ error: gqlErr as DocErrorType,
+ },
+ // The right case (it was a GraphQL Error)
+ (networkErr) =>
+ <GQLError<DocErrorType>>{
+ type: "network_error",
+ error: networkErr,
+ }
+ )
+ )
+ )
)
- )
- )
- )
- if (finalOptions.noPolling) {
- gqlQuery.toPromise().then((result) => {
- data.value = processResult(result)
- })
- } else {
- subscription = pipe(
- gqlQuery,
- subscribe((result) => {
- data.value = processResult(result)
- })
+ loading.value = false
+ })
+ ).unsubscribe
)
}
})
- onBeforeUnmount(() => {
- subscription?.unsubscribe()
+ const execute = (updatedVars?: DocVarType) => {
+ if (updatedVars) {
+ args.variables = updatedVars as any
+ }
+
+ isPaused.value = false
+ }
+
+ const response = reactive({
+ loading,
+ data,
+ isStale,
+ execute,
+ })
+
+ watchEffect(() => {
+ console.log(JSON.stringify(response))
})
- return reactive({
- loading: computed(() => !data.value),
- data: data!,
- }) as
- | {
- loading: false
- data: DataType
- }
- | { loading: true }
+ return response
}
export const runMutation = <
diff --git a/packages/hoppscotch-app/helpers/backend/gql/queries/pendingInvites.graphql b/packages/hoppscotch-app/helpers/backend/gql/queries/pendingInvites.graphql
new file mode 100644
index 000000000..bbc10779b
--- /dev/null
+++ b/packages/hoppscotch-app/helpers/backend/gql/queries/pendingInvites.graphql
@@ -0,0 +1,10 @@
+query GetPendingInvites($teamID: ID!) {
+ team(teamID: $teamID) {
+ id
+ teamInvitations {
+ inviteeRole
+ inviteeEmail
+ id
+ }
+ }
+}