Skip to content

Commit

Permalink
chore: cleanup selectors (#10078)
Browse files Browse the repository at this point in the history
Signed-off-by: Matt Krick <[email protected]>
Co-authored-by: Jordan Husney <[email protected]>
  • Loading branch information
mattkrick and jordanh authored Aug 6, 2024
1 parent 01884e8 commit 0a6534d
Show file tree
Hide file tree
Showing 39 changed files with 280 additions and 330 deletions.
12 changes: 6 additions & 6 deletions codegen.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"LoginsPayload": "./types/LoginsPayload#LoginsPayloadSource",
"MeetingTemplate": "../../database/types/MeetingTemplate#default as IMeetingTemplate",
"NewMeeting": "../../postgres/types/Meeting#AnyMeeting",
"Organization": "../public/types/Organization#OrganizationSource",
"Organization": "../../postgres/types/index#Organization as OrganizationDB",
"PingableServices": "./types/PingableServices#PingableServicesSource",
"ProcessRecurrenceSuccess": "./types/ProcessRecurrenceSuccess#ProcessRecurrenceSuccessSource",
"RemoveAuthIdentitySuccess": "./types/RemoveAuthIdentitySuccess#RemoveAuthIdentitySuccessSource",
Expand All @@ -30,7 +30,7 @@
"SignupsPayload": "./types/SignupsPayload#SignupsPayloadSource",
"StartTrialSuccess": "./types/StartTrialSuccess#StartTrialSuccessSource",
"StripeFailPaymentPayload": "./mutations/stripeFailPayment#StripeFailPaymentPayloadSource",
"Team": "../public/types/Team#TeamSource",
"Team": "../../postgres/types/index#Team as TeamDB",
"UpdateOrgFeatureFlagSuccess": "./types/UpdateOrgFeatureFlagSuccess#UpdateOrgFeatureFlagSuccessSource",
"UpgradeToTeamTierSuccess": "./mutations/upgradeToTeamTier#UpgradeToTeamTierSuccessSource",
"User": "../../postgres/types/IUser#default as IUser",
Expand Down Expand Up @@ -116,7 +116,7 @@
"NotifyResponseReplied": "../../database/types/NotifyResponseReplied#default as NotifyResponseRepliedDB",
"NotifyTaskInvolves": "../../database/types/NotificationTaskInvolves#default",
"NotifyTeamArchived": "../../database/types/NotificationTeamArchived#default",
"Organization": "./types/Organization#OrganizationSource",
"Organization": "../../postgres/types/index#Organization as OrganizationDB",
"TemplateScaleValue": "./types/TemplateScaleValue#TemplateScaleValueSource as TemplateScaleValueSourceDB",
"SuggestedAction": "../../postgres/types/index#SuggestedAction as SuggestedActionDB",
"TemplateScale": "../../postgres/types/index#TemplateScale as TemplateScaleDB",
Expand All @@ -137,7 +137,7 @@
"RemoveTeamMemberIntegrationAuthSuccess": "./types/RemoveTeamMemberIntegrationAuthPayload#RemoveTeamMemberIntegrationAuthSuccessSource",
"RequestToJoinDomainSuccess": "./types/RequestToJoinDomainSuccess#RequestToJoinDomainSuccessSource",
"ResetReflectionGroupsSuccess": "./types/ResetReflectionGroupsSuccess#ResetReflectionGroupsSuccessSource",
"RetroReflection": "./types/RetroReflection#RetroReflectionSource",
"RetroReflection": "../../postgres/types/index#RetroReflection as RetroReflectionDB",
"RetroReflectionGroup": "./types/RetroReflectionGroup#RetroReflectionGroupSource",
"RetrospectiveMeeting": "../../database/types/MeetingRetrospective#default",
"RetrospectiveMeetingMember": "../../database/types/RetroMeetingMember#default",
Expand All @@ -152,7 +152,7 @@
"StartTeamPromptSuccess": "./types/StartTeamPromptSuccess#StartTeamPromptSuccessSource",
"StripeFailPaymentPayload": "./types/StripeFailPaymentPayload#StripeFailPaymentPayloadSource",
"Task": "../../database/types/Task#default",
"Team": "./types/Team#TeamSource",
"Team": "../../postgres/types/index#Team as TeamDB",
"TeamPromptMeetingSettings": "../../database/types/MeetingSettingsTeamPrompt#default as MeetingSettingsTeamPromptDB",
"TeamHealthPhase": "./types/TeamHealthPhase#TeamHealthPhaseSource",
"TeamHealthStage": "./types/TeamHealthStage#TeamHealthStageSource",
Expand All @@ -164,7 +164,7 @@
"TeamMemberIntegrations": "./types/TeamMemberIntegrations#TeamMemberIntegrationsSource",
"TeamPromptMeeting": "../../database/types/MeetingTeamPrompt#default as MeetingTeamPromptDB",
"TeamPromptMeetingMember": "../../database/types/TeamPromptMeetingMember#default as TeamPromptMeetingMemberDB",
"TeamPromptResponse": "../../postgres/queries/getTeamPromptResponsesByIds#TeamPromptResponse",
"TeamPromptResponse": "../../postgres/types/index#TeamPromptResponse as TeamPromptResponseDB",
"TemplateDimension": "../../postgres/types/index#TemplateDimension as TemplateDimensionDB",
"TimelineEventTeamPromptComplete": "./types/TimelineEventTeamPromptComplete#TimelineEventTeamPromptCompleteSource",
"ToggleFavoriteTemplateSuccess": "./types/ToggleFavoriteTemplateSuccess#ToggleFavoriteTemplateSuccessSource",
Expand Down
4 changes: 0 additions & 4 deletions packages/client/types/generics.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type {SelectQueryBuilder} from 'kysely'
import type {MutableRefObject} from 'react'
import type {RecordProxy} from 'relay-runtime'

Expand Down Expand Up @@ -109,6 +108,3 @@ declare global {
findLastIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number
}
}

export type ExtractTypeFromQueryBuilderSelect<T extends (...args: any[]) => any> =
ReturnType<T> extends SelectQueryBuilder<infer _A, infer _B, infer X> ? X : never
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {DataLoaderWorker} from '../../graphql/graphql'
import {OrganizationSource} from '../../graphql/public/types/Organization'
import {Organization} from '../../postgres/types'
import {analytics} from '../../utils/analytics/analytics'
import {getStripeManager} from '../../utils/stripe'

const sendEnterpriseOverageEvent = async (
organization: OrganizationSource,
organization: Organization,
dataLoader: DataLoaderWorker
) => {
const manager = getStripeManager()
Expand All @@ -31,7 +31,7 @@ const sendEnterpriseOverageEvent = async (
}

const handleEnterpriseOrgQuantityChanges = async (
paidOrgs: OrganizationSource[],
paidOrgs: Organization[],
dataLoader: DataLoaderWorker
) => {
const enterpriseOrgs = paidOrgs.filter((org) => org.tier === 'enterprise')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {OrganizationSource} from '../../graphql/public/types/Organization'
import {Organization} from '../../postgres/types'
import updateSubscriptionQuantity from './updateSubscriptionQuantity'

const handleTeamOrgQuantityChanges = async (paidOrgs: OrganizationSource[]) => {
const handleTeamOrgQuantityChanges = async (paidOrgs: Organization[]) => {
const teamOrgs = paidOrgs.filter((org) => org.tier === 'team')
if (teamOrgs.length === 0) return

Expand Down
4 changes: 2 additions & 2 deletions packages/server/billing/helpers/teamLimitsCheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import NotificationTeamsLimitExceeded from '../../database/types/NotificationTea
import scheduleTeamLimitsJobs from '../../database/types/scheduleTeamLimitsJobs'
import {DataLoaderWorker} from '../../graphql/graphql'
import publishNotification from '../../graphql/public/mutations/helpers/publishNotification'
import {OrganizationSource} from '../../graphql/public/types/Organization'
import getActiveTeamCountByTeamIds from '../../graphql/public/types/helpers/getActiveTeamCountByTeamIds'
import {getFeatureTier} from '../../graphql/types/helpers/getFeatureTier'
import {domainHasActiveDeals} from '../../hubSpot/hubSpotApi'
import getKysely from '../../postgres/getKysely'
import getTeamIdsByOrgIds from '../../postgres/queries/getTeamIdsByOrgIds'
import {Organization} from '../../postgres/types'
import {getBillingLeadersByOrgId} from '../../utils/getBillingLeadersByOrgId'
import sendToSentry from '../../utils/sendToSentry'
import removeTeamsLimitObjects from './removeTeamsLimitObjects'
Expand All @@ -36,7 +36,7 @@ const enableUsageStats = async (userIds: string[], orgId: string) => {
}

const sendWebsiteNotifications = async (
organization: OrganizationSource,
organization: Organization,
userIds: string[],
dataLoader: DataLoaderWorker
) => {
Expand Down
6 changes: 0 additions & 6 deletions packages/server/database/types/Reactable.ts

This file was deleted.

41 changes: 6 additions & 35 deletions packages/server/dataloader/customLoaderMakers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import getRethink, {RethinkSchema} from '../database/rethinkDriver'
import {RDatum} from '../database/stricterR'
import MeetingSettingsTeamPrompt from '../database/types/MeetingSettingsTeamPrompt'
import MeetingTemplate from '../database/types/MeetingTemplate'
import {Reactable, ReactableEnum} from '../database/types/Reactable'
import Task, {TaskStatusEnum} from '../database/types/Task'
import getFileStoreManager from '../fileStorage/getFileStoreManager'
import {ReactableEnum} from '../graphql/public/resolverTypes'
import {SAMLSource} from '../graphql/public/types/SAML'
import {TeamSource} from '../graphql/public/types/Team'
import getKysely from '../postgres/getKysely'
import {TeamMeetingTemplate} from '../postgres/pg.d'
import {IGetLatestTaskEstimatesQueryResult} from '../postgres/queries/generated/getLatestTaskEstimatesQuery'
Expand All @@ -27,7 +26,8 @@ import getLatestTaskEstimates from '../postgres/queries/getLatestTaskEstimates'
import getMeetingTaskEstimates, {
MeetingTaskEstimatesResult
} from '../postgres/queries/getMeetingTaskEstimates'
import {OrganizationUser} from '../postgres/types'
import {selectTeams} from '../postgres/select'
import {OrganizationUser, Team} from '../postgres/types'
import {AnyMeeting, MeetingTypeEnum} from '../postgres/types/Meeting'
import {Logger} from '../utils/Logger'
import getRedis from '../utils/getRedis'
Expand All @@ -36,7 +36,6 @@ import NullableDataLoader from './NullableDataLoader'
import RootDataLoader, {RegisterDependsOn} from './RootDataLoader'
import normalizeArrayResults from './normalizeArrayResults'
import normalizeResults from './normalizeResults'
import {selectTeams} from './primaryKeyLoaderMakers'

export interface MeetingSettingsKey {
teamId: string
Expand All @@ -49,7 +48,7 @@ export interface MeetingTemplateKey {
}

export interface ReactablesKey {
id: string
id: string | number
type: ReactableEnum
}

Expand All @@ -64,12 +63,6 @@ export interface UserTasksKey {
includeUnassigned?: boolean
}

const reactableLoaders = [
{type: 'COMMENT', loader: 'comments'},
{type: 'REFLECTION', loader: 'retroReflections'},
{type: 'RESPONSE', loader: 'teamPromptResponses'}
] as const

export const serializeUserTasksKey = (key: UserTasksKey) => {
const {userIds, teamIds, first, after, archived, statusFilters, filterQuery} = key
const parts = [
Expand Down Expand Up @@ -146,28 +139,6 @@ export const meetingTaskEstimates = (parent: RootDataLoader) => {
)
}

export const reactables = (parent: RootDataLoader, dependsOn: RegisterDependsOn) => {
dependsOn(reactableLoaders.map((a) => a.loader))
return new DataLoader<ReactablesKey, Reactable, string>(
async (keys) => {
const reactableResults = (await Promise.all(
reactableLoaders.map(async (val) => {
const ids = keys.filter((key) => key.type === val.type).map(({id}) => id)
return parent.get(val.loader).loadMany(ids)
})
)) as Reactable[][]
const reactables = reactableResults.flat()
const keyIds = keys.map(({id}) => id)
const ret = normalizeResults(keyIds, reactables)
return ret
},
{
...parent.dataLoaderOptions,
cacheKeyFn: (key) => `${key.id}:${key.type}`
}
)
}

export const userTasks = (parent: RootDataLoader, dependsOn: RegisterDependsOn) => {
dependsOn('tasks')
return new DataLoader<UserTasksKey, Task[], string>(
Expand Down Expand Up @@ -779,7 +750,7 @@ export const isOrgVerified = (parent: RootDataLoader, dependsOn: RegisterDepends

export const autoJoinTeamsByOrgId = (parent: RootDataLoader, dependsOn: RegisterDependsOn) => {
dependsOn('teams')
return new DataLoader<string, TeamSource[], string>(
return new DataLoader<string, Team[], string>(
async (orgIds) => {
const verificationResults = await parent.get('isOrgVerified').loadMany(orgIds)
const verifiedOrgIds = orgIds.filter((_, index) => verificationResults[index])
Expand Down Expand Up @@ -873,7 +844,7 @@ export const fileStoreAsset = (parent: RootDataLoader) => {
}

export const meetingCount = (parent: RootDataLoader, dependsOn: RegisterDependsOn) => {
dependsOn('selectTeams')
dependsOn('newMeetings')
return new DataLoader<{teamId: string; meetingType: MeetingTypeEnum}, number, string>(
async (keys) => {
const r = await getRethink()
Expand Down
11 changes: 10 additions & 1 deletion packages/server/dataloader/foreignKeyLoaderMakers.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import getKysely from '../postgres/getKysely'
import {getTeamPromptResponsesByMeetingIds} from '../postgres/queries/getTeamPromptResponsesByMeetingIds'
import {
selectOrganizations,
selectRetroReflections,
selectSuggestedAction,
selectTeams,
selectTemplateDimension,
selectTemplateScale,
selectTimelineEvent
} from '../postgres/select'
import {foreignKeyLoaderMaker} from './foreignKeyLoaderMaker'
import {selectOrganizations, selectRetroReflections, selectTeams} from './primaryKeyLoaderMakers'

export const teamsByOrgIds = foreignKeyLoaderMaker('teams', 'orgId', (orgIds) =>
selectTeams().where('orgId', 'in', orgIds).where('isArchived', '=', false).execute()
Expand Down Expand Up @@ -161,3 +164,9 @@ export const suggestedActionsByUserId = foreignKeyLoaderMaker(
return selectSuggestedAction().where('userId', 'in', userIds).execute()
}
)

export const teamPromptResponsesByMeetingId = foreignKeyLoaderMaker(
'teamPromptResponses',
'meetingId',
getTeamPromptResponsesByMeetingIds
)
99 changes: 7 additions & 92 deletions packages/server/dataloader/primaryKeyLoaderMakers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import {getDiscussionsByIds} from '../postgres/queries/getDiscussionsByIds'
import {getDomainJoinRequestsByIds} from '../postgres/queries/getDomainJoinRequestsByIds'
import getMeetingSeriesByIds from '../postgres/queries/getMeetingSeriesByIds'
import getMeetingTemplatesByIds from '../postgres/queries/getMeetingTemplatesByIds'
import {getTeamPromptResponsesByIds} from '../postgres/queries/getTeamPromptResponsesByIds'
import getTemplateRefsByIds from '../postgres/queries/getTemplateRefsByIds'
import {getUsersByIds} from '../postgres/queries/getUsersByIds'
import {
selectOrganizations,
selectRetroReflections,
selectSuggestedAction,
selectTeamPromptResponses,
selectTeams,
selectTemplateDimension,
selectTemplateScale,
selectTemplateScaleRef,
Expand All @@ -17,44 +20,6 @@ import {primaryKeyLoaderMaker} from './primaryKeyLoaderMaker'

export const users = primaryKeyLoaderMaker(getUsersByIds)

export const selectTeams = () =>
getKysely()
.selectFrom('Team')
.select([
'autoJoin',
'createdAt',
'createdBy',
'id',
'insightsUpdatedAt',
'isArchived',
'isOnboardTeam',
'isPaid',
'kudosEmojiUnicode',
'lastMeetingType',
'lockMessageHTML',
'meetingEngagement',
'mostUsedEmojis',
'name',
'orgId',
'qualAIMeetingsCount',
'tier',
'topRetroTemplates',
'trialStartDate',
'updatedAt'
])
.select(({fn}) => [
fn<
{
dimensionName: string
cloudId: string
projectKey: string
issueKey: string
fieldName: string
fieldType: string
fieldId: string
}[]
>('to_json', ['jiraDimensionFields']).as('jiraDimensionFields')
])
export const teams = primaryKeyLoaderMaker((ids: readonly string[]) => {
return selectTeams().where('id', 'in', ids).execute()
})
Expand All @@ -63,7 +28,9 @@ export const templateRefs = primaryKeyLoaderMaker(getTemplateRefsByIds)
export const templateScaleRefs = primaryKeyLoaderMaker((ids: readonly string[]) => {
return selectTemplateScaleRef().where('id', 'in', ids).execute()
})
export const teamPromptResponses = primaryKeyLoaderMaker(getTeamPromptResponsesByIds)
export const teamPromptResponses = primaryKeyLoaderMaker(async (ids: readonly number[]) => {
return selectTeamPromptResponses().where('id', 'in', ids).execute()
})
export const meetingSeries = primaryKeyLoaderMaker(getMeetingSeriesByIds)
export const meetingTemplates = primaryKeyLoaderMaker(getMeetingTemplatesByIds)
export const domainJoinRequests = primaryKeyLoaderMaker(getDomainJoinRequestsByIds)
Expand All @@ -76,28 +43,6 @@ export const retroReflectionGroups = primaryKeyLoaderMaker((ids: readonly string
return getKysely().selectFrom('RetroReflectionGroup').selectAll().where('id', 'in', ids).execute()
})

export const selectRetroReflections = () =>
getKysely()
.selectFrom('RetroReflection')
.select([
'id',
'content',
'createdAt',
'creatorId',
'isActive',
'meetingId',
'plaintextContent',
'promptId',
'reflectionGroupId',
'sentimentScore',
'sortOrder',
'updatedAt'
])
.select(({fn}) => [
fn<{lemma: string; salience: number; name: string}[]>('to_json', ['entities']).as('entities'),
fn<{id: string; userId: string}[]>('to_json', ['reactjis']).as('reactjis')
])

export const retroReflections = primaryKeyLoaderMaker((ids: readonly string[]) => {
return selectRetroReflections().where('id', 'in', ids).execute()
})
Expand All @@ -106,36 +51,6 @@ export const timelineEvents = primaryKeyLoaderMaker((ids: readonly string[]) =>
return selectTimelineEvent().where('id', 'in', ids).execute()
})

export const selectOrganizations = () =>
getKysely()
.selectFrom('Organization')
.select([
'id',
'activeDomain',
'isActiveDomainTouched',
'createdAt',
'name',
'payLaterClickCount',
'periodEnd',
'periodStart',
'picture',
'showConversionModal',
'stripeId',
'stripeSubscriptionId',
'upcomingInvoiceEmailSentAt',
'tier',
'tierLimitExceededAt',
'trialStartDate',
'scheduledLockAt',
'lockedAt',
'updatedAt',
'featureFlags'
])
.select(({fn}) => [
fn<{brand: string; expiry: string; last4: number} | null>('to_json', ['creditCard']).as(
'creditCard'
)
])
export const organizations = primaryKeyLoaderMaker((ids: readonly string[]) => {
return selectOrganizations().where('id', 'in', ids).execute()
})
Expand Down
Loading

0 comments on commit 0a6534d

Please sign in to comment.