|
| 1 | +import { NextFunction, Request, Response } from 'express' |
| 2 | + |
| 3 | +import { |
| 4 | + buildSegmentActivityTypes, |
| 5 | + isSegmentSubproject, |
| 6 | +} from '@crowd/data-access-layer/src/segments' |
| 7 | +import { getServiceChildLogger } from '@crowd/logging' |
| 8 | + |
| 9 | +import { IRepositoryOptions } from '../database/repositories/IRepositoryOptions' |
1 | 10 | import SegmentRepository from '../database/repositories/segmentRepository' |
2 | 11 |
|
3 | | -export async function segmentMiddleware(req, res, next) { |
| 12 | +const log = getServiceChildLogger('segmentMiddleware') |
| 13 | + |
| 14 | +export async function segmentMiddleware(req: Request, _res: Response, next: NextFunction) { |
4 | 15 | try { |
5 | 16 | let segments: any = null |
6 | | - const segmentRepository = new SegmentRepository(req) |
7 | | - |
8 | | - if (req.params.segmentId) { |
9 | | - // for param requests, segments will be in the url |
10 | | - segments = { rows: await segmentRepository.findInIds([req.params.segmentId]) } |
11 | | - } else if (req.query.segments) { |
12 | | - // for get requests, segments will be in query |
13 | | - segments = { rows: await segmentRepository.findInIds(req.query.segments) } |
14 | | - } else if (req.body.segments) { |
15 | | - // for post and put requests, segments will be in body |
16 | | - segments = { rows: await segmentRepository.findInIds(req.body.segments) } |
| 17 | + const segmentRepository = new SegmentRepository(req as unknown as IRepositoryOptions) |
| 18 | + |
| 19 | + // Note: req.params is NOT available here. This middleware is registered via app.use(), |
| 20 | + // which runs before Express matches a specific route and populates req.params. |
| 21 | + // Any check on req.params (e.g. req.params.segmentId) would always be undefined. |
| 22 | + // Route handlers that need a specific segment by ID (e.g. GET /segment/:segmentId) |
| 23 | + // read req.params directly and ignore req.currentSegments entirely — so the |
| 24 | + // resolution below is harmless for those endpoints. |
| 25 | + const querySegments = toStringArray(req.query.segments) |
| 26 | + const bodySegments = toStringArray((req.body as Record<string, unknown>)?.segments) |
| 27 | + |
| 28 | + if (querySegments.length > 0) { |
| 29 | + segments = { |
| 30 | + rows: await resolveToLeafSegments(segmentRepository, querySegments, req), |
| 31 | + } |
| 32 | + } else if (bodySegments.length > 0) { |
| 33 | + const resolvedRows = await resolveToLeafSegments(segmentRepository, bodySegments, req) |
| 34 | + segments = { rows: resolvedRows } |
17 | 35 | } else { |
18 | 36 | segments = await segmentRepository.querySubprojects({ limit: 1, offset: 0 }) |
19 | 37 | } |
20 | 38 |
|
21 | | - req.currentSegments = segments.rows |
| 39 | + const options = req as unknown as IRepositoryOptions |
| 40 | + options.currentSegments = segments.rows |
22 | 41 |
|
23 | 42 | next() |
24 | 43 | } catch (error) { |
25 | 44 | next(error) |
26 | 45 | } |
27 | 46 | } |
| 47 | + |
| 48 | +/** |
| 49 | + * Safely extracts a string[] from an unknown query/body value. |
| 50 | + * Rejects ParsedQs objects (e.g. ?segments[key]=val) that would cause type confusion. |
| 51 | + */ |
| 52 | +function toStringArray(value: unknown): string[] { |
| 53 | + if (value === undefined || value === null) return [] |
| 54 | + const items = Array.isArray(value) ? value : [value] |
| 55 | + return items.filter((v): v is string => typeof v === 'string') |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Resolves segment IDs to their leaf sub-projects. |
| 60 | + * |
| 61 | + * If all provided IDs are already sub-projects (leaf level), returns them as-is |
| 62 | + * without any extra DB call — fully backward-compatible with the current behavior. |
| 63 | + * |
| 64 | + * If any ID is a project or project group (non-leaf), expands it to all its |
| 65 | + * active sub-projects and applies populateSegmentRelations to match the shape |
| 66 | + * that downstream services expect from req.currentSegments. |
| 67 | + */ |
| 68 | +async function resolveToLeafSegments( |
| 69 | + segmentRepository: SegmentRepository, |
| 70 | + segmentIds: string[], |
| 71 | + req: Request, |
| 72 | +) { |
| 73 | + const fetched = await segmentRepository.findInIds(segmentIds) |
| 74 | + |
| 75 | + const nonLeaf = fetched.filter((s) => !isSegmentSubproject(s)) |
| 76 | + |
| 77 | + const segmentLevel = (s: any) => { |
| 78 | + if (s.grandparentSlug) return 'subproject' |
| 79 | + if (s.parentSlug) return 'project' |
| 80 | + return 'projectGroup' |
| 81 | + } |
| 82 | + |
| 83 | + const nullActivityTypes = (record: any) => ({ ...record, activityTypes: null }) |
| 84 | + |
| 85 | + if (nonLeaf.length === 0) { |
| 86 | + // All inputs are already leaf subprojects. findInIds() already called populateSegmentRelations |
| 87 | + // on each record, which includes a cloneDeep(DEFAULT_ACTIVITY_TYPE_SETTINGS) per segment. |
| 88 | + // Keep activityTypes on the first record only; null the rest to release those clones. |
| 89 | + // getSegmentActivityTypes merges with lodash.merge which skips null values, so the first |
| 90 | + // record's activityTypes (default + its custom types) is sufficient for display purposes. |
| 91 | + const [first, ...rest] = fetched |
| 92 | + log.debug( |
| 93 | + { |
| 94 | + api: `${req.method} ${req.path}`, |
| 95 | + usedInDbQueries: fetched.map((s) => ({ id: s.id, name: s.name, level: segmentLevel(s) })), |
| 96 | + }, |
| 97 | + `All segments are already leaf — used as-is in DB queries`, |
| 98 | + ) |
| 99 | + return first ? [first, ...rest.map(nullActivityTypes)] : [] |
| 100 | + } |
| 101 | + |
| 102 | + const leafRecords = await segmentRepository.getSegmentSubprojects(segmentIds) |
| 103 | + |
| 104 | + log.debug( |
| 105 | + { |
| 106 | + api: `${req.method} ${req.path}`, |
| 107 | + input_segments: nonLeaf.map((s) => ({ id: s.id, name: s.name, level: segmentLevel(s) })), |
| 108 | + resolved_count: leafRecords.length, |
| 109 | + }, |
| 110 | + 'Non-leaf segments resolved to leaf sub-projects', |
| 111 | + ) |
| 112 | + |
| 113 | + if (leafRecords.length === 0) return [] |
| 114 | + |
| 115 | + // getSegmentSubprojects returns raw DB rows (no populateSegmentRelations/cloneDeep). |
| 116 | + // Build activityTypes from the first leaf only (one cloneDeep of DEFAULT_ACTIVITY_TYPE_SETTINGS). |
| 117 | + // null the rest — getSegmentActivityTypes merges all and lodash.merge skips null sources. |
| 118 | + const [first, ...rest] = leafRecords |
| 119 | + return [ |
| 120 | + { ...first, activityTypes: buildSegmentActivityTypes(first) }, |
| 121 | + ...rest.map(nullActivityTypes), |
| 122 | + ] |
| 123 | +} |
0 commit comments