|
1 | | -const { readFile } = require('fs/promises') |
2 | 1 | const { Readable } = require('stream') |
3 | 2 |
|
4 | 3 | const { Implementation } = require('@open-keystone/fields') |
5 | 4 | const cuid = require('cuid') |
6 | 5 |
|
| 6 | +const { ExternalContent } = require('@open-condo/keystone/fieldsUtils') |
7 | 7 | const { getLogger } = require('@open-condo/keystone/logging') |
8 | | -const { FILE_META_TYPE, isFileMeta } = require('@open-condo/keystone/utils/externalContentFieldType') |
9 | 8 |
|
10 | | -const { FileContentLoader } = require('./FileContentLoader') |
11 | | -const { validateFilePath } = require('./utils') |
12 | 9 |
|
| 10 | +const { FILE_META_TYPE, isFileMeta, resolveExternalContentValue } = ExternalContent |
13 | 11 | const logger = getLogger('ExternalContent') |
14 | 12 |
|
15 | | -// WeakMap to store unique loader keys per adapter instance |
16 | | -// This prevents loader key collisions when multiple adapters have the same folder name |
17 | | -const adapterLoaderKeys = new WeakMap() |
18 | | - |
19 | 13 | const DEFAULT_FORMAT = 'json' |
20 | | -// Default max size: 10MB |
21 | | -const DEFAULT_MAX_SIZE_BYTES = 10 * 1024 * 1024 |
22 | | - |
| 14 | +const DEFAULT_MAX_SIZE_BYTES = 10 * 1024 * 1024 // Default max size: 10MB |
23 | 15 | const DEFAULT_PROCESSORS = { |
24 | 16 | json: { |
25 | 17 | graphQLInputType: 'JSON', |
@@ -53,89 +45,6 @@ const DEFAULT_PROCESSORS = { |
53 | 45 | }, |
54 | 46 | } |
55 | 47 |
|
56 | | -/** |
57 | | - * Reads file contents for ExternalContent field from the provided adapter. |
58 | | - * |
59 | | - * Why not just `fetch(file.publicUrl)`? |
60 | | - * - `publicUrl()` often returns an indirect URL like `/api/files/...` served by our app. |
61 | | - * - Those endpoints frequently require authentication (cookie / Authorization / signature). |
62 | | - * - Field resolvers do not have a browser session and should not depend on request-specific auth. |
63 | | - * |
64 | | - * Therefore: |
65 | | - * - For cloud adapters we use `adapter.acl.generateUrl(...)` to get a short-lived signed *direct* URL |
66 | | - * (S3/OBS), and fetch bytes from it without cookies. |
67 | | - * - For local adapter we read from filesystem directly via `adapter.src`. |
68 | | - * |
69 | | - * @param {*} adapter File adapter instance passed into field config |
70 | | - * @param {{ filename: string, mimetype?: string, originalFilename?: string }} fileMeta Stored file-meta object |
71 | | - * @returns {Promise<Buffer>} |
72 | | - */ |
73 | | -async function readFromAdapter (adapter, fileMeta) { |
74 | | - const filename = fileMeta.filename |
75 | | - |
76 | | - // Local adapter (from `packages/keystone/fileAdapter/fileAdapter.js`) |
77 | | - if (typeof adapter?.src === 'string') { |
78 | | - const fullPath = validateFilePath(adapter.src, filename) |
79 | | - return Buffer.from(await readFile(fullPath)) |
80 | | - } |
81 | | - |
82 | | - // Cloud adapters provide acl.generateUrl which returns a signed, time-limited direct URL. |
83 | | - // It does not require auth cookies (unlike indirect /api/files/... urls from publicUrl()). |
84 | | - if (adapter?.acl && typeof adapter.acl.generateUrl === 'function' && adapter.folder) { |
85 | | - const directUrl = adapter.acl.generateUrl({ |
86 | | - filename: `${adapter.folder}/${filename}`, |
87 | | - mimetype: fileMeta.mimetype, |
88 | | - originalFilename: fileMeta.originalFilename, |
89 | | - }) |
90 | | - |
91 | | - if (!directUrl || typeof directUrl !== 'string') { |
92 | | - throw new Error(`Invalid URL generated for file: ${filename}`) |
93 | | - } |
94 | | - |
95 | | - const res = await fetch(directUrl) |
96 | | - if (!res.ok) { |
97 | | - throw new Error(`Fetch failed with status ${res.status} for file: ${filename}`) |
98 | | - } |
99 | | - const buf = Buffer.from(await res.arrayBuffer()) |
100 | | - return buf |
101 | | - } |
102 | | - |
103 | | - throw new Error('ExternalContent: unsupported file adapter for read') |
104 | | -} |
105 | | - |
106 | | -/** |
107 | | - * Get or create a FileContentLoader for the given adapter. |
108 | | - * |
109 | | - * Implements lazy initialization: creates loader on first access and reuses it for subsequent calls. |
110 | | - * Each adapter instance gets its own unique loader (keyed by adapter instance via WeakMap). |
111 | | - * |
112 | | - * @param {Object} context - GraphQL context object |
113 | | - * @param {Object} adapter - File adapter instance |
114 | | - * @param {number} [batchDelayMs] - Time window in milliseconds to collect requests before executing batch |
115 | | - * @returns {FileContentLoader} Loader instance for this adapter |
116 | | - */ |
117 | | -function getOrCreateLoader (context, adapter, batchDelayMs) { |
118 | | - // Initialize loaders map if not exists |
119 | | - if (!context._externalContentLoaders) { |
120 | | - context._externalContentLoaders = new Map() |
121 | | - } |
122 | | - |
123 | | - // Use adapter instance as key via WeakMap to prevent collisions |
124 | | - // This ensures different adapter instances get different loaders even if they have the same folder |
125 | | - if (!adapterLoaderKeys.has(adapter)) { |
126 | | - adapterLoaderKeys.set(adapter, Symbol('loader')) |
127 | | - } |
128 | | - const loaderKey = adapterLoaderKeys.get(adapter) |
129 | | - |
130 | | - // Return existing loader or create new one |
131 | | - if (!context._externalContentLoaders.has(loaderKey)) { |
132 | | - const options = batchDelayMs !== undefined ? { batchDelayMs } : undefined |
133 | | - context._externalContentLoaders.set(loaderKey, new FileContentLoader(adapter, options)) |
134 | | - } |
135 | | - |
136 | | - return context._externalContentLoaders.get(loaderKey) |
137 | | -} |
138 | | - |
139 | 48 | class ExternalContentImplementation extends Implementation { |
140 | 49 | constructor (path, { |
141 | 50 | adapter, |
@@ -222,71 +131,30 @@ class ExternalContentImplementation extends Implementation { |
222 | 131 | /** |
223 | 132 | * Resolves the field value for GraphQL output by reading the file content from storage. |
224 | 133 | * |
225 | | - * For backward compatibility, returns inline JSON objects directly if they don't have file-meta structure. |
226 | | - * For file-meta objects, fetches the file content and deserializes it. |
227 | | - * |
228 | | - * Performance optimization: |
229 | | - * - Uses DataLoader for batching and caching when context is available (GraphQL queries) |
230 | | - * - Batches multiple file reads into single operation (10ms window) |
231 | | - * - Caches results within request to prevent duplicate reads |
232 | | - * - Falls back to direct readFromAdapter for non-GraphQL usage |
233 | | - * |
234 | | - * Note: This reads the entire file into memory. For very large files (10MB+), this could cause |
235 | | - * memory pressure under load. Current use case (BillingReceipt.raw) typically has files <1MB. |
| 134 | + * Delegates to resolveExternalContentValue utility which handles: |
| 135 | + * - Backward compatibility with inline JSON objects |
| 136 | + * - File-meta object resolution with DataLoader batching |
| 137 | + * - Graceful handling of missing files |
236 | 138 | * |
237 | 139 | * @returns {Object} Field resolver mapping |
238 | 140 | */ |
239 | 141 | gqlOutputFieldResolvers () { |
240 | 142 | return { |
241 | 143 | [this.path]: async (item, args, context) => { |
242 | | - let value = item?.[this.path] |
243 | | - if (value === null || typeof value === 'undefined') return value |
244 | | - |
245 | | - // Parse JSON string if needed (database stores serialized JSON) |
246 | | - if (typeof value === 'string') { |
247 | | - try { |
248 | | - value = JSON.parse(value) |
249 | | - } catch (err) { |
250 | | - // If parsing fails, return the string as-is (backward compatibility) |
251 | | - return value |
252 | | - } |
253 | | - } |
254 | | - |
255 | | - // Backward compatibility: old `Json` field stored raw object directly in DB |
256 | | - if (!isFileMeta(value)) return value |
257 | | - |
258 | | - // Use DataLoader for batching and caching when context is available |
259 | | - let buf |
260 | | - try { |
261 | | - if (context) { |
262 | | - const loader = getOrCreateLoader(context, this.adapter, this.batchDelayMs) |
263 | | - buf = await loader.load(value) |
264 | | - } else { |
265 | | - // Fallback to direct read for non-GraphQL usage (tests, scripts, etc.) |
266 | | - buf = await readFromAdapter(this.adapter, value) |
267 | | - } |
268 | | - } catch (err) { |
269 | | - // Handle missing files gracefully - return null instead of crashing |
270 | | - if (err.code === 'ENOENT') { |
271 | | - const itemId = item?.id || 'unknown' |
272 | | - logger.warn({ msg: 'File not found for ExternalContent field', field: this.path, itemId, filename: value?.filename || 'unknown' }) |
273 | | - return null |
274 | | - } |
275 | | - throw err |
276 | | - } |
277 | | - |
278 | | - // Handle null buffer from FileContentLoader (missing file) |
279 | | - if (buf === null) { |
280 | | - return null |
281 | | - } |
282 | | - |
| 144 | + const value = item?.[this.path] |
283 | 145 | try { |
284 | | - const raw = buf.toString('utf-8') |
285 | | - return this.deserialize(raw) |
| 146 | + return await resolveExternalContentValue(value, { |
| 147 | + adapter: this.adapter, |
| 148 | + deserialize: this.deserialize, |
| 149 | + context, |
| 150 | + batchDelayMs: this.batchDelayMs, |
| 151 | + fieldPath: this.path, |
| 152 | + item, |
| 153 | + }) |
286 | 154 | } catch (err) { |
287 | 155 | const itemId = item?.id || 'unknown' |
288 | | - const errMsg = err?.message || String(err) |
289 | | - throw new Error(`Failed to deserialize ${this.path} for item ${itemId}: ${errMsg}`) |
| 156 | + logger.warn({ msg: 'Error resolving ExternalContent field', field: this.path, itemId, err }) |
| 157 | + throw err |
290 | 158 | } |
291 | 159 | }, |
292 | 160 | } |
@@ -388,13 +256,13 @@ class ExternalContentImplementation extends Implementation { |
388 | 256 |
|
389 | 257 | // Save first, then delete old file. |
390 | 258 | // This prevents losing the previous file if save() fails. |
391 | | - |
| 259 | + |
392 | 260 | const payload = this.serialize(nextValue) |
393 | 261 | const payloadSizeBytes = Buffer.byteLength(String(payload), 'utf-8') |
394 | | - |
| 262 | + |
395 | 263 | // Validate size limit after serialization |
396 | 264 | this._validatePayloadSize(payloadSizeBytes) |
397 | | - |
| 265 | + |
398 | 266 | const stream = Readable.from([Buffer.from(String(payload), 'utf-8')]) |
399 | 267 |
|
400 | 268 | const prefix = listKey || 'item' |
|
0 commit comments