Skip to content

Commit 0b0dddd

Browse files
committed
Fetch media attachment point in hydration
This keeps the app from having to go to the DB again, just to know if it should apply logic.
1 parent ea7f2b6 commit 0b0dddd

File tree

2 files changed

+35
-12
lines changed

2 files changed

+35
-12
lines changed

src/components/file/media/media.dto.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
ServerException,
2121
simpleSwitch,
2222
} from '~/common';
23+
import { BaseNode } from '~/core/database/results';
2324
import { FileVersion } from '../dto';
2425

2526
export type AnyMedia = Image | Video | Audio;
@@ -78,6 +79,9 @@ export class Media extends MediaUserMetadata {
7879

7980
readonly file: IdOf<FileVersion>;
8081

82+
/** The resource that holds the root file node that this media is attached to */
83+
readonly attachedTo: [resource: BaseNode, relation: string];
84+
8185
@Field(() => String)
8286
readonly mimeType: string;
8387
}

src/components/file/media/media.repository.ts

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Injectable } from '@nestjs/common';
22
import { inArray, node, or, Query, relation } from 'cypher-query-builder';
3-
import { RequireAtLeastOne } from 'type-fest';
3+
import { Except, RequireAtLeastOne } from 'type-fest';
44
import {
55
EnhancedResource,
66
generateId,
@@ -47,20 +47,39 @@ export class MediaRepository extends CommonRepository {
4747

4848
protected hydrate() {
4949
return (query: Query) =>
50-
query.return<{ dto: AnyMedia }>(
51-
merge('node', {
52-
__typename: 'node.type',
53-
file: 'fv.id',
54-
dimensions: {
55-
width: 'node.width',
56-
height: 'node.height',
57-
},
58-
}).as('dto'),
59-
);
50+
query
51+
.subQuery('fv', (sub) =>
52+
sub
53+
.comment('Find root file node')
54+
.subQuery('fv', (sub2) =>
55+
sub2
56+
.raw('MATCH p=(fv)-[:parent*]->(node:FileNode)')
57+
.return('node as root')
58+
.orderBy('length(p)', 'DESC')
59+
.raw('LIMIT 1'),
60+
)
61+
.comment('Get resource holding root file node')
62+
.raw('MATCH (resource:BaseNode)-[rel]->(root)')
63+
.raw('WHERE not resource:FileNode')
64+
.return('[resource, type(rel)] as attachedTo')
65+
.raw('LIMIT 1'),
66+
)
67+
.return<{ dto: AnyMedia }>(
68+
merge('node', {
69+
__typename: 'node.type',
70+
file: 'fv.id',
71+
dimensions: {
72+
width: 'node.width',
73+
height: 'node.height',
74+
},
75+
attachedTo: 'attachedTo',
76+
}).as('dto'),
77+
);
6078
}
6179

6280
async save(
63-
input: RequireAtLeastOne<Pick<AnyMedia, 'id' | 'file'>> & Partial<AnyMedia>,
81+
input: RequireAtLeastOne<Pick<AnyMedia, 'id' | 'file'>> &
82+
Partial<Except<AnyMedia, 'attachedTo'>>,
6483
) {
6584
const res = input.__typename
6685
? EnhancedResource.of(resolveMedia(input as AnyMedia))

0 commit comments

Comments
 (0)