Skip to content

Commit

Permalink
chore(server): core IoC 37 - legacyGetStreamsFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
fabis94 committed Oct 9, 2024
1 parent 8550f1a commit ab6fa84
Show file tree
Hide file tree
Showing 8 changed files with 111 additions and 98 deletions.
12 changes: 12 additions & 0 deletions packages/server/modules/core/domain/streams/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ import { ContextResourceAccessRules } from '@/modules/core/helpers/token'
import { MaybeNullOrUndefined, Nullable, Optional, StreamRoles } from '@speckle/shared'
import { Knex } from 'knex'

export type LegacyGetStreams = (params: {
cursor?: string | Date | null | undefined
limit: number
orderBy?: string | null | undefined
visibility?: string | null | undefined
searchQuery?: string | null | undefined
streamIdWhitelist?: string[] | null | undefined
workspaceIdWhitelist?: string[] | null | undefined
offset?: MaybeNullOrUndefined<number>
publicOnly?: MaybeNullOrUndefined<boolean>
}) => Promise<{ streams: Stream[]; totalCount: number; cursorDate: Nullable<Date> }>

export type GetStreams = (
streamIds: string[],
options?: Partial<{
Expand Down
5 changes: 3 additions & 2 deletions packages/server/modules/core/graph/resolvers/streams.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
getStreams,
getStreamUsers,
favoriteStream,
getFavoriteStreamsCollection,
Expand Down Expand Up @@ -33,7 +32,8 @@ import {
revokeStreamPermissionsFactory,
grantStreamPermissionsFactory,
getDiscoverableStreamsPage,
countDiscoverableStreamsFactory
countDiscoverableStreamsFactory,
legacyGetStreamsFactory
} from '@/modules/core/repositories/streams'
import {
createStreamReturnRecordFactory,
Expand Down Expand Up @@ -161,6 +161,7 @@ const getDiscoverableStreams = getDiscoverableStreamsFactory({
getDiscoverableStreamsPage: getDiscoverableStreamsPage({ db }),
countDiscoverableStreams: countDiscoverableStreamsFactory({ db })
})
const getStreams = legacyGetStreamsFactory({ db })

const getUserStreamsCore = async (
forOtherUser: boolean,
Expand Down
87 changes: 86 additions & 1 deletion packages/server/modules/core/repositories/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ import {
GetOnboardingBaseStream,
GetDiscoverableStreamsParams,
CountDiscoverableStreams,
GetDiscoverableStreamsPage
GetDiscoverableStreamsPage,
LegacyGetStreams
} from '@/modules/core/domain/streams/operations'
export type { StreamWithOptionalRole, StreamWithCommitId }

Expand Down Expand Up @@ -1241,3 +1242,87 @@ export const getRolesByUserIdFactory =
}
return await query
}

/**
* @deprecated Use getStreams() from the repository directly
*/
export const legacyGetStreamsFactory =
(deps: { db: Knex }): LegacyGetStreams =>
async ({
cursor,
limit,
orderBy,
visibility,
searchQuery,
streamIdWhitelist,
workspaceIdWhitelist,
offset,
publicOnly
}) => {
const query = tables.streams(deps.db)
const countQuery = tables.streams(deps.db)

if (searchQuery) {
const whereFunc: Knex.QueryCallback = function () {
this.where('streams.name', 'ILIKE', `%${searchQuery}%`).orWhere(
'streams.description',
'ILIKE',
`%${searchQuery}%`
)
}
query.where(whereFunc)
countQuery.where(whereFunc)
}

if (publicOnly) {
visibility = 'public'
}

if (visibility && visibility !== 'all') {
if (!['private', 'public'].includes(visibility))
throw new Error('Stream visibility should be either private, public or all')
const isPublic = visibility === 'public'
const publicFunc: Knex.QueryCallback = function () {
this.where({ isPublic })
}
query.andWhere(publicFunc)
countQuery.andWhere(publicFunc)
}

if (streamIdWhitelist?.length) {
query.whereIn('id', streamIdWhitelist)
countQuery.whereIn('id', streamIdWhitelist)
}

if (workspaceIdWhitelist?.length) {
query.whereIn('workspaceId', workspaceIdWhitelist)
countQuery.whereIn('workspaceId', workspaceIdWhitelist)
}

const [res] = await countQuery.count()
const count = parseInt(res.count + '')

if (!count) return { streams: [], totalCount: 0, cursorDate: null }

orderBy = orderBy || 'updatedAt,desc'

const [columnName, order] = orderBy.split(',')

if (cursor) query.where(columnName, order === 'desc' ? '<' : '>', cursor)

query.orderBy(`${columnName}`, order).limit(limit)
if (offset) {
query.offset(offset)
}

const rows = await query

const cursorDate = rows.length
? rows.slice(-1)[0][columnName as keyof StreamRecord]
: null
return {
streams: rows,
totalCount: count,
cursorDate: cursorDate as Nullable<Date>
}
}
3 changes: 2 additions & 1 deletion packages/server/modules/core/services/admin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import db from '@/db/knex'
import { ServerInviteGraphQLReturnType } from '@/modules/core/helpers/graphTypes'
import { StreamRecord, UserRecord } from '@/modules/core/helpers/types'
import { legacyGetStreamsFactory } from '@/modules/core/repositories/streams'
import { listUsers, countUsers } from '@/modules/core/repositories/users'
import { getStreams } from '@/modules/core/services/streams'
import { ServerInviteRecord } from '@/modules/serverinvites/domain/types'
import {
countServerInvitesFactory,
Expand Down Expand Up @@ -103,6 +103,7 @@ export const adminProjectList = async (
args: AdminProjectListArgs & { streamIdWhitelist?: string[] }
): Promise<Collection<StreamRecord>> => {
const parsedCursor = args.cursor ? parseCursorToDate(args.cursor) : null
const getStreams = legacyGetStreamsFactory({ db })
const { streams, totalCount, cursorDate } = await getStreams({
...args,
searchQuery: args.query,
Expand Down
89 changes: 1 addition & 88 deletions packages/server/modules/core/services/streams.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'
const _ = require('lodash')
const { Streams, StreamAcl, knex } = require('@/modules/core/dbSchema')
const { StreamAcl, knex } = require('@/modules/core/dbSchema')
const {
getFavoritedStreams,
getFavoritedStreamsCount,
Expand All @@ -24,93 +24,6 @@ const {
module.exports = {
setStreamFavorited,

/**
* @param {Object} p
* @param {string | Date | null} [p.cursor]
* @param {number} p.limit
* @param {string | null} [p.orderBy]
* @param {string | null} [p.visibility]
* @param {string | null} [p.searchQuery]
* @param {string[] | null} [p.streamIdWhitelist]
* @param {string[] | null} [p.workspaceIdWhitelist]
* @param {number | null} [p.offset]
* @param {boolean | null} [p.publicOnly]
* @deprecated Use getStreams() from the repository directly
*/
async getStreams({
cursor,
limit,
orderBy,
visibility,
searchQuery,
streamIdWhitelist,
workspaceIdWhitelist,
offset,
publicOnly
}) {
const query = knex.select().from('streams')

const countQuery = Streams.knex()

if (searchQuery) {
const whereFunc = function () {
this.where('streams.name', 'ILIKE', `%${searchQuery}%`).orWhere(
'streams.description',
'ILIKE',
`%${searchQuery}%`
)
}
query.where(whereFunc)
countQuery.where(whereFunc)
}

if (publicOnly) {
visibility = 'public'
}

if (visibility && visibility !== 'all') {
if (!['private', 'public'].includes(visibility))
throw new Error('Stream visibility should be either private, public or all')
const isPublic = visibility === 'public'
const publicFunc = function () {
this.where({ isPublic })
}
query.andWhere(publicFunc)
countQuery.andWhere(publicFunc)
}

if (streamIdWhitelist?.length) {
query.whereIn('id', streamIdWhitelist)
countQuery.whereIn('id', streamIdWhitelist)
}

if (workspaceIdWhitelist?.length) {
query.whereIn('workspaceId', workspaceIdWhitelist)
countQuery.whereIn('workspaceId', workspaceIdWhitelist)
}

const [res] = await countQuery.count()
const count = parseInt(res.count)

if (!count) return { streams: [], totalCount: 0 }

orderBy = orderBy || 'updatedAt,desc'

const [columnName, order] = orderBy.split(',')

if (cursor) query.where(columnName, order === 'desc' ? '<' : '>', cursor)

query.orderBy(`${columnName}`, order).limit(limit)
if (offset) {
query.offset(offset)
}

const rows = await query

const cursorDate = rows.length ? rows.slice(-1)[0][columnName] : null
return { streams: rows, totalCount: count, cursorDate }
},

/**
* @returns {Promise<{role: string, id: string, name: string, company: string, avatar: string}[]>}
*/
Expand Down
3 changes: 2 additions & 1 deletion packages/server/modules/workspaces/events/eventListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import {
deleteProjectRoleFactory,
getStreamFactory,
legacyGetStreamsFactory,
upsertProjectRoleFactory
} from '@/modules/core/repositories/streams'
import {
Expand Down Expand Up @@ -42,7 +43,6 @@ import {
queryAllWorkspaceProjectsFactory,
getWorkspaceRoleToDefaultProjectRoleMappingFactory
} from '@/modules/workspaces/services/projects'
import { getStreams } from '@/modules/core/services/streams'
import { withTransaction } from '@/modules/shared/helpers/dbHelper'
import { findVerifiedEmailsByUserIdFactory } from '@/modules/core/repositories/userEmails'
import { GetStream } from '@/modules/core/domain/streams/operations'
Expand Down Expand Up @@ -217,6 +217,7 @@ export const initializeEventListenersFactory =
({ db }: { db: Knex }) =>
() => {
const eventBus = getEventBus()
const getStreams = legacyGetStreamsFactory({ db })
const quitCbs = [
ProjectsEmitter.listen(ProjectEvents.Created, async (payload) => {
const onProjectCreated = onProjectCreatedFactory({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {
getStreamFactory,
deleteStreamFactory,
revokeStreamPermissionsFactory,
grantStreamPermissionsFactory
grantStreamPermissionsFactory,
legacyGetStreamsFactory
} from '@/modules/core/repositories/streams'
import { getUser, getUsers } from '@/modules/core/repositories/users'
import { getStreams } from '@/modules/core/services/streams'
import { InviteCreateValidationError } from '@/modules/serverinvites/errors'
import {
deleteAllResourceInvitesFactory,
Expand Down Expand Up @@ -396,6 +396,7 @@ export = FF_WORKSPACES_MODULE_ENABLED
)

// Delete workspace and associated resources (i.e. invites)
const getStreams = legacyGetStreamsFactory({ db })
const deleteWorkspace = deleteWorkspaceFactory({
deleteWorkspace: repoDeleteWorkspaceFactory({ db }),
deleteProject: deleteStream,
Expand Down
5 changes: 2 additions & 3 deletions packages/server/modules/workspaces/services/projects.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { StreamRecord } from '@/modules/core/helpers/types'
import { getStreams as serviceGetStreams } from '@/modules/core/services/streams'
import { getUserStreams } from '@/modules/core/repositories/streams'
import {
GetWorkspace,
Expand All @@ -23,12 +22,12 @@ import { chunk } from 'lodash'
import { Roles, StreamRoles } from '@speckle/shared'
import { orderByWeight } from '@/modules/shared/domain/rolesAndScopes/logic'
import coreUserRoles from '@/modules/core/roles'
import { LegacyGetStreams } from '@/modules/core/domain/streams/operations'

export const queryAllWorkspaceProjectsFactory = ({
getStreams
}: {
// TODO: Core service factory functions
getStreams: typeof serviceGetStreams
getStreams: LegacyGetStreams
}): QueryAllWorkspaceProjects =>
async function* queryAllWorkspaceProjects({
workspaceId
Expand Down

0 comments on commit ab6fa84

Please sign in to comment.