@adminforth/upload 1.0.29 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ChangeLog.md CHANGED
@@ -1,4 +1,9 @@
1
1
 
2
+ ## [1.0.30] - 2024-12-26
3
+
4
+ ### Improved
5
+
6
+ - Add 'record' param for s3Path callback in edit mode
2
7
 
3
8
  ## [1.0.24] - 2023-12-24
4
9
 
@@ -70,7 +70,9 @@ import { computed, ref, onMounted, watch } from 'vue'
70
70
  import { callAdminForthApi } from '@/utils'
71
71
  import { IconMagic } from '@iconify-prerendered/vue-mdi';
72
72
  import { useI18n } from 'vue-i18n';
73
+ import { useRoute } from 'vue-router';
73
74
 
75
+ const route = useRoute();
74
76
  const { t } = useI18n();
75
77
 
76
78
  const inputId = computed(() => `dropzone-file-${props.meta.pluginInstanceId}`);
@@ -233,6 +235,7 @@ const onFileChange = async (e) => {
233
235
  contentType: type,
234
236
  size,
235
237
  originalExtension: extension,
238
+ recordPk: route?.params?.primaryKey,
236
239
  },
237
240
  });
238
241
 
@@ -70,7 +70,9 @@ import { computed, ref, onMounted, watch } from 'vue'
70
70
  import { callAdminForthApi } from '@/utils'
71
71
  import { IconMagic } from '@iconify-prerendered/vue-mdi';
72
72
  import { useI18n } from 'vue-i18n';
73
+ import { useRoute } from 'vue-router';
73
74
 
75
+ const route = useRoute();
74
76
  const { t } = useI18n();
75
77
 
76
78
  const inputId = computed(() => `dropzone-file-${props.meta.pluginInstanceId}`);
@@ -233,6 +235,7 @@ const onFileChange = async (e) => {
233
235
  contentType: type,
234
236
  size,
235
237
  originalExtension: extension,
238
+ recordPk: route?.params?.primaryKey,
236
239
  },
237
240
  });
238
241
 
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
11
11
  import { ExpirationStatus, GetObjectCommand, PutObjectCommand, S3 } from '@aws-sdk/client-s3';
12
- import { AdminForthPlugin, suggestIfTypo } from "adminforth";
12
+ import { AdminForthPlugin, Filters, suggestIfTypo } from "adminforth";
13
13
  import { Readable } from "stream";
14
14
  import { RateLimiter } from "adminforth";
15
15
  const ADMINFORTH_NOT_YET_USED_TAG = 'adminforth-candidate-for-cleanup';
@@ -105,7 +105,7 @@ export default class UploadPlugin extends AdminForthPlugin {
105
105
  const { pathColumnName } = this.options;
106
106
  const pathColumnIndex = resourceConfig.columns.findIndex((column) => column.name === pathColumnName);
107
107
  if (pathColumnIndex === -1) {
108
- throw new Error(`Column with name "${pathColumnName}" not found in resource "${resourceConfig.name}"`);
108
+ throw new Error(`Column with name "${pathColumnName}" not found in resource "${resourceConfig.label}"`);
109
109
  }
110
110
  if ((_a = this.options.generation) === null || _a === void 0 ? void 0 : _a.fieldsForContext) {
111
111
  (_b = this.options.generation) === null || _b === void 0 ? void 0 : _b.fieldsForContext.forEach((field) => {
@@ -283,8 +283,8 @@ export default class UploadPlugin extends AdminForthPlugin {
283
283
  return { ok: true };
284
284
  }));
285
285
  // add edit postSave hook to delete old file and remove tag from new file
286
- resourceConfig.hooks.edit.afterSave.push((_s) => __awaiter(this, [_s], void 0, function* ({ record, oldRecord }) {
287
- if (record[virtualColumn.name] || record[virtualColumn.name] === null) {
286
+ resourceConfig.hooks.edit.afterSave.push((_s) => __awaiter(this, [_s], void 0, function* ({ updates, oldRecord }) {
287
+ if (updates[virtualColumn.name] || updates[virtualColumn.name] === null) {
288
288
  const s3 = new S3({
289
289
  credentials: {
290
290
  accessKeyId: this.options.s3AccessKeyId,
@@ -313,12 +313,12 @@ export default class UploadPlugin extends AdminForthPlugin {
313
313
  console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${oldRecord[pathColumnName]}. File will not be auto-cleaned up`, e);
314
314
  }
315
315
  }
316
- if (record[virtualColumn.name] !== null) {
316
+ if (updates[virtualColumn.name] !== null) {
317
317
  // remove tag from new file
318
318
  // in this case we let it crash if it fails: this is a new file which just was uploaded.
319
319
  yield s3.putObjectTagging({
320
320
  Bucket: this.options.s3Bucket,
321
- Key: record[pathColumnName],
321
+ Key: updates[pathColumnName],
322
322
  Tagging: {
323
323
  TagSet: []
324
324
  }
@@ -339,14 +339,20 @@ export default class UploadPlugin extends AdminForthPlugin {
339
339
  method: 'POST',
340
340
  path: `/plugin/${this.pluginInstanceId}/get_s3_upload_url`,
341
341
  handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
342
- var _b;
343
- const { originalFilename, contentType, size, originalExtension } = body;
342
+ var _b, _c;
343
+ const { originalFilename, contentType, size, originalExtension, recordPk } = body;
344
344
  if (this.options.allowedFileExtensions && !this.options.allowedFileExtensions.includes(originalExtension)) {
345
345
  return {
346
346
  error: `File extension "${originalExtension}" is not allowed, allowed extensions are: ${this.options.allowedFileExtensions.join(', ')}`
347
347
  };
348
348
  }
349
- const s3Path = this.options.s3Path({ originalFilename, originalExtension, contentType });
349
+ let record = undefined;
350
+ if (recordPk) {
351
+ // get record by recordPk
352
+ const pkName = (_b = this.resourceConfig.columns.find((column) => column.primaryKey)) === null || _b === void 0 ? void 0 : _b.name;
353
+ record = yield this.adminforth.resource(this.resourceConfig.resourceId).get([Filters.EQ(pkName, recordPk)]);
354
+ }
355
+ const s3Path = this.options.s3Path({ originalFilename, originalExtension, contentType, record });
350
356
  if (s3Path.startsWith('/')) {
351
357
  throw new Error('s3Path should not start with /, please adjust s3path function to not return / at the start of the path');
352
358
  }
@@ -370,7 +376,7 @@ export default class UploadPlugin extends AdminForthPlugin {
370
376
  unhoistableHeaders: new Set(['x-amz-tagging']),
371
377
  });
372
378
  let previewUrl;
373
- if ((_b = this.options.preview) === null || _b === void 0 ? void 0 : _b.previewUrl) {
379
+ if ((_c = this.options.preview) === null || _c === void 0 ? void 0 : _c.previewUrl) {
374
380
  previewUrl = this.options.preview.previewUrl({ s3Path });
375
381
  }
376
382
  else if (this.options.s3ACL === 'public-read') {
@@ -411,15 +417,15 @@ export default class UploadPlugin extends AdminForthPlugin {
411
417
  server.endpoint({
412
418
  method: 'POST',
413
419
  path: `/plugin/${this.pluginInstanceId}/generate_images`,
414
- handler: (_c) => __awaiter(this, [_c], void 0, function* ({ body, headers }) {
415
- var _d, _e;
420
+ handler: (_d) => __awaiter(this, [_d], void 0, function* ({ body, headers }) {
421
+ var _e, _f;
416
422
  const { prompt } = body;
417
423
  if (this.options.generation.provider !== 'openai-dall-e') {
418
424
  throw new Error(`Provider ${this.options.generation.provider} is not supported`);
419
425
  }
420
- if ((_d = this.options.generation.rateLimit) === null || _d === void 0 ? void 0 : _d.limit) {
426
+ if ((_e = this.options.generation.rateLimit) === null || _e === void 0 ? void 0 : _e.limit) {
421
427
  // rate limit
422
- const { error } = RateLimiter.checkRateLimit(this.pluginInstanceId, (_e = this.options.generation.rateLimit) === null || _e === void 0 ? void 0 : _e.limit, this.adminforth.auth.getClientIp(headers));
428
+ const { error } = RateLimiter.checkRateLimit(this.pluginInstanceId, (_f = this.options.generation.rateLimit) === null || _f === void 0 ? void 0 : _f.limit, this.adminforth.auth.getClientIp(headers));
423
429
  if (error) {
424
430
  return { error: this.options.generation.rateLimit.errorMessage };
425
431
  }
@@ -455,7 +461,7 @@ export default class UploadPlugin extends AdminForthPlugin {
455
461
  server.endpoint({
456
462
  method: 'GET',
457
463
  path: `/plugin/${this.pluginInstanceId}/cors-proxy`,
458
- handler: (_f) => __awaiter(this, [_f], void 0, function* ({ query, response }) {
464
+ handler: (_g) => __awaiter(this, [_g], void 0, function* ({ query, response }) {
459
465
  const { url } = query;
460
466
  const resp = yield fetch(url);
461
467
  response.setHeader('Content-Type', resp.headers.get('Content-Type'));
package/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  import { PluginOptions } from './types.js';
3
3
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
4
4
  import { ExpirationStatus, GetObjectCommand, ObjectCannedACL, PutObjectCommand, S3 } from '@aws-sdk/client-s3';
5
- import { AdminForthPlugin, AdminForthResourceColumn, AdminForthResourcePages, IAdminForth, IHttpServer, suggestIfTypo } from "adminforth";
5
+ import { AdminForthPlugin, AdminForthResourceColumn, AdminForthResource, Filters, IAdminForth, IHttpServer, suggestIfTypo } from "adminforth";
6
6
  import { Readable } from "stream";
7
7
  import { RateLimiter } from "adminforth";
8
8
 
@@ -94,7 +94,7 @@ export default class UploadPlugin extends AdminForthPlugin {
94
94
  record[`previewUrl_${this.pluginInstanceId}`] = previewUrl;
95
95
  }
96
96
 
97
- async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: any) {
97
+ async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
98
98
  super.modifyResourceConfig(adminforth, resourceConfig);
99
99
  // after column to store the path of the uploaded file, add new VirtualColumn,
100
100
  // show only in edit and create views
@@ -102,7 +102,7 @@ export default class UploadPlugin extends AdminForthPlugin {
102
102
  const { pathColumnName } = this.options;
103
103
  const pathColumnIndex = resourceConfig.columns.findIndex((column: any) => column.name === pathColumnName);
104
104
  if (pathColumnIndex === -1) {
105
- throw new Error(`Column with name "${pathColumnName}" not found in resource "${resourceConfig.name}"`);
105
+ throw new Error(`Column with name "${pathColumnName}" not found in resource "${resourceConfig.label}"`);
106
106
  }
107
107
 
108
108
  if (this.options.generation?.fieldsForContext) {
@@ -315,9 +315,9 @@ export default class UploadPlugin extends AdminForthPlugin {
315
315
 
316
316
 
317
317
  // add edit postSave hook to delete old file and remove tag from new file
318
- resourceConfig.hooks.edit.afterSave.push(async ({ record, oldRecord }: { record: any, oldRecord: any }) => {
318
+ resourceConfig.hooks.edit.afterSave.push(async ({ updates, oldRecord }: { updates: any, oldRecord: any }) => {
319
319
 
320
- if (record[virtualColumn.name] || record[virtualColumn.name] === null) {
320
+ if (updates[virtualColumn.name] || updates[virtualColumn.name] === null) {
321
321
  const s3 = new S3({
322
322
  credentials: {
323
323
  accessKeyId: this.options.s3AccessKeyId,
@@ -347,12 +347,12 @@ export default class UploadPlugin extends AdminForthPlugin {
347
347
  console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${oldRecord[pathColumnName]}. File will not be auto-cleaned up`, e);
348
348
  }
349
349
  }
350
- if (record[virtualColumn.name] !== null) {
350
+ if (updates[virtualColumn.name] !== null) {
351
351
  // remove tag from new file
352
352
  // in this case we let it crash if it fails: this is a new file which just was uploaded.
353
353
  await s3.putObjectTagging({
354
354
  Bucket: this.options.s3Bucket,
355
- Key: record[pathColumnName],
355
+ Key: updates[pathColumnName],
356
356
  Tagging: {
357
357
  TagSet: []
358
358
  }
@@ -376,7 +376,7 @@ export default class UploadPlugin extends AdminForthPlugin {
376
376
  method: 'POST',
377
377
  path: `/plugin/${this.pluginInstanceId}/get_s3_upload_url`,
378
378
  handler: async ({ body }) => {
379
- const { originalFilename, contentType, size, originalExtension } = body;
379
+ const { originalFilename, contentType, size, originalExtension, recordPk } = body;
380
380
 
381
381
  if (this.options.allowedFileExtensions && !this.options.allowedFileExtensions.includes(originalExtension)) {
382
382
  return {
@@ -384,7 +384,16 @@ export default class UploadPlugin extends AdminForthPlugin {
384
384
  };
385
385
  }
386
386
 
387
- const s3Path: string = this.options.s3Path({ originalFilename, originalExtension, contentType });
387
+ let record = undefined;
388
+ if (recordPk) {
389
+ // get record by recordPk
390
+ const pkName = this.resourceConfig.columns.find((column: any) => column.primaryKey)?.name;
391
+ record = await this.adminforth.resource(this.resourceConfig.resourceId).get(
392
+ [Filters.EQ(pkName, recordPk)]
393
+ )
394
+ }
395
+
396
+ const s3Path: string = this.options.s3Path({ originalFilename, originalExtension, contentType, record });
388
397
  if (s3Path.startsWith('/')) {
389
398
  throw new Error('s3Path should not start with /, please adjust s3path function to not return / at the start of the path');
390
399
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/upload",
3
- "version": "1.0.29",
3
+ "version": "1.0.30",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/types.ts CHANGED
@@ -50,11 +50,16 @@ export type PluginOptions = {
50
50
  * example:
51
51
  *
52
52
  * ```typescript
53
- * s3Path: ({record, originalFilename}) => `/aparts/${record.id}/${originalFilename}`
53
+ * s3Path: ({originalFilename}) => `/aparts/${originalFilename}`
54
54
  * ```
55
55
  *
56
56
  */
57
- s3Path: ({originalFilename, originalExtension, contentType}) => string,
57
+ s3Path: ({originalFilename, originalExtension, contentType, record }: {
58
+ originalFilename: string,
59
+ originalExtension: string,
60
+ contentType: string,
61
+ record?: any,
62
+ }) => string,
58
63
 
59
64
 
60
65
  preview: {