@adminforth/upload 1.5.0 → 2.0.1

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/README.md CHANGED
@@ -4,4 +4,4 @@
4
4
 
5
5
  Allows to upload files to Amazon S3 bucket from adminforth application.
6
6
 
7
- ## For usage, see [AdminForth Upload Documentation](https://adminforth.dev/docs/tutorial/Plugins/upload/)
7
+ ## For usage, see [AdminForth Upload Documentation](https://adminforth.dev/docs/tutorial/Plugins/upload/)
package/build.log CHANGED
@@ -11,5 +11,5 @@ custom/preview.vue
11
11
  custom/tsconfig.json
12
12
  custom/uploader.vue
13
13
 
14
- sent 43,165 bytes received 134 bytes 86,598.00 bytes/sec
15
- total size is 42,676 speedup is 0.99
14
+ sent 44,046 bytes received 134 bytes 88,360.00 bytes/sec
15
+ total size is 43,557 speedup is 0.99
@@ -58,7 +58,7 @@
58
58
  } */
59
59
  </style>
60
60
  <script setup>
61
- import { ref, computed , onMounted, watch} from 'vue'
61
+ import { ref, computed , onMounted, watch, nextTick} from 'vue'
62
62
  import mediumZoom from 'medium-zoom'
63
63
  import { useRoute } from 'vue-router'
64
64
 
@@ -71,6 +71,30 @@ const props = defineProps({
71
71
  meta: Object,
72
72
  })
73
73
 
74
+ const trueContentType = ref(null);
75
+
76
+ onMounted(async () => {
77
+ // try to get HEAD request
78
+ try {
79
+ const response = await fetch(url.value, {
80
+ method: 'HEAD',
81
+ });
82
+ const ct = response.headers.get('Content-Type');
83
+ if (ct) {
84
+ trueContentType.value = ct;
85
+ }
86
+ } catch (e) {
87
+ console.error('fetch error for getting content type, please check CORS allowed for HEAD request', e);
88
+ }
89
+ });
90
+
91
+ const contentType = computed(() => {
92
+ if (trueContentType.value) {
93
+ return trueContentType.value;
94
+ }
95
+ return guessedContentType.value;
96
+ });
97
+
74
98
  const route = useRoute();
75
99
  const url = computed(() => {
76
100
  return props.record[`previewUrl_${props.meta.pluginInstanceId}`];
@@ -95,11 +119,11 @@ const minWidth = computed(() => {
95
119
  });
96
120
  // since we have no way to know the content type of the file, we will try to guess it from extension
97
121
  // for better experience probably we should check whether user saves content type in the database and use it here
98
- const contentType = computed(() => {
122
+ const guessedContentType = computed(() => {
99
123
  if (!url.value) {
100
124
  return null;
101
125
  }
102
- const u = new URL(url.value);
126
+ const u = new URL(url.value, url.value.startsWith('http') ? undefined : location.origin);
103
127
  return guessContentType(u.pathname);
104
128
  });
105
129
 
@@ -117,14 +141,18 @@ function guessContentType(url) {
117
141
  }
118
142
 
119
143
 
120
- onMounted(async () => {
121
-
122
- if (contentType.value?.startsWith('image')) {
144
+ watch([contentType], async ([contentType]) => {
145
+ // since content type might change after true guessing (HEAD request might be slow) we need to try initializing zoom again
146
+ if (zoom.value) {
147
+ zoom.value.detach();
148
+ }
149
+ await nextTick();
150
+ if (contentType?.startsWith('image')) {
123
151
  zoom.value = mediumZoom(img.value, {
124
152
  margin: 24,
125
153
  });
126
154
  }
127
155
 
128
- });
156
+ }, { immediate: true });
129
157
 
130
158
  </script>
@@ -273,7 +273,7 @@ const onFileChange = async (e) => {
273
273
  });
274
274
  if (!success) {
275
275
  adminforth.alert({
276
- messageHtml: `<div>${t('Sorry but the file was not uploaded because of S3 Request Error:')}</div>
276
+ messageHtml: `<div>${t('Sorry but the file was not uploaded because of internal storage Request Error:')}</div>
277
277
  <pre style="white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; max-width: 100%;">${
278
278
  xhr.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;')
279
279
  }</pre>`,
@@ -58,7 +58,7 @@
58
58
  } */
59
59
  </style>
60
60
  <script setup>
61
- import { ref, computed , onMounted, watch} from 'vue'
61
+ import { ref, computed , onMounted, watch, nextTick} from 'vue'
62
62
  import mediumZoom from 'medium-zoom'
63
63
  import { useRoute } from 'vue-router'
64
64
 
@@ -71,6 +71,30 @@ const props = defineProps({
71
71
  meta: Object,
72
72
  })
73
73
 
74
+ const trueContentType = ref(null);
75
+
76
+ onMounted(async () => {
77
+ // try to get HEAD request
78
+ try {
79
+ const response = await fetch(url.value, {
80
+ method: 'HEAD',
81
+ });
82
+ const ct = response.headers.get('Content-Type');
83
+ if (ct) {
84
+ trueContentType.value = ct;
85
+ }
86
+ } catch (e) {
87
+ console.error('fetch error for getting content type, please check CORS allowed for HEAD request', e);
88
+ }
89
+ });
90
+
91
+ const contentType = computed(() => {
92
+ if (trueContentType.value) {
93
+ return trueContentType.value;
94
+ }
95
+ return guessedContentType.value;
96
+ });
97
+
74
98
  const route = useRoute();
75
99
  const url = computed(() => {
76
100
  return props.record[`previewUrl_${props.meta.pluginInstanceId}`];
@@ -95,11 +119,11 @@ const minWidth = computed(() => {
95
119
  });
96
120
  // since we have no way to know the content type of the file, we will try to guess it from extension
97
121
  // for better experience probably we should check whether user saves content type in the database and use it here
98
- const contentType = computed(() => {
122
+ const guessedContentType = computed(() => {
99
123
  if (!url.value) {
100
124
  return null;
101
125
  }
102
- const u = new URL(url.value);
126
+ const u = new URL(url.value, url.value.startsWith('http') ? undefined : location.origin);
103
127
  return guessContentType(u.pathname);
104
128
  });
105
129
 
@@ -117,14 +141,18 @@ function guessContentType(url) {
117
141
  }
118
142
 
119
143
 
120
- onMounted(async () => {
121
-
122
- if (contentType.value?.startsWith('image')) {
144
+ watch([contentType], async ([contentType]) => {
145
+ // since content type might change after true guessing (HEAD request might be slow) we need to try initializing zoom again
146
+ if (zoom.value) {
147
+ zoom.value.detach();
148
+ }
149
+ await nextTick();
150
+ if (contentType?.startsWith('image')) {
123
151
  zoom.value = mediumZoom(img.value, {
124
152
  margin: 24,
125
153
  });
126
154
  }
127
155
 
128
- });
156
+ }, { immediate: true });
129
157
 
130
158
  </script>
@@ -273,7 +273,7 @@ const onFileChange = async (e) => {
273
273
  });
274
274
  if (!success) {
275
275
  adminforth.alert({
276
- messageHtml: `<div>${t('Sorry but the file was not uploaded because of S3 Request Error:')}</div>
276
+ messageHtml: `<div>${t('Sorry but the file was not uploaded because of internal storage Request Error:')}</div>
277
277
  <pre style="white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; max-width: 100%;">${
278
278
  xhr.responseText.replace(/</g, '&lt;').replace(/>/g, '&gt;')
279
279
  }</pre>`,
package/dist/index.js CHANGED
@@ -24,7 +24,8 @@ export default class UploadPlugin extends AdminForthPlugin {
24
24
  }
25
25
  setupLifecycleRule() {
26
26
  return __awaiter(this, void 0, void 0, function* () {
27
- this.options.storage.adapter.setupLifecycle();
27
+ const adapterUserUniqueRepresentation = `${this.resourceConfig.resourceId}-${this.pluginInstanceId}`;
28
+ this.options.storageAdapter.setupLifecycle(adapterUserUniqueRepresentation);
28
29
  });
29
30
  }
30
31
  genPreviewUrl(record) {
@@ -34,7 +35,7 @@ export default class UploadPlugin extends AdminForthPlugin {
34
35
  record[`previewUrl_${this.pluginInstanceId}`] = this.options.preview.previewUrl({ filePath: record[this.options.pathColumnName] });
35
36
  return;
36
37
  }
37
- const previewUrl = yield this.options.storage.adapter.getDownloadUrl(record[this.options.pathColumnName], 1800);
38
+ const previewUrl = yield this.options.storageAdapter.getDownloadUrl(record[this.options.pathColumnName], 1800);
38
39
  record[`previewUrl_${this.pluginInstanceId}`] = previewUrl;
39
40
  });
40
41
  }
@@ -45,6 +46,7 @@ export default class UploadPlugin extends AdminForthPlugin {
45
46
  return __awaiter(this, void 0, void 0, function* () {
46
47
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
47
48
  _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
49
+ this.resourceConfig = resourceConfig;
48
50
  // after column to store the path of the uploaded file, add new VirtualColumn,
49
51
  // show only in edit and create views
50
52
  // use component uploader.vue
@@ -148,7 +150,7 @@ export default class UploadPlugin extends AdminForthPlugin {
148
150
  if (record[pathColumnName]) {
149
151
  process.env.HEAVY_DEBUG && console.log('🪥🪥 remove ObjectTagging', record[pathColumnName]);
150
152
  // let it crash if it fails: this is a new file which just was uploaded.
151
- yield this.options.storage.adapter.markKeyForNotDeletation(record[pathColumnName]);
153
+ yield this.options.storageAdapter.markKeyForNotDeletation(record[pathColumnName]);
152
154
  }
153
155
  return { ok: true };
154
156
  }));
@@ -182,7 +184,7 @@ export default class UploadPlugin extends AdminForthPlugin {
182
184
  resourceConfig.hooks.delete.afterSave.push((_a) => __awaiter(this, [_a], void 0, function* ({ record }) {
183
185
  if (record[pathColumnName]) {
184
186
  try {
185
- yield this.options.storage.adapter.markKeyForDeletation(record[pathColumnName]);
187
+ yield this.options.storageAdapter.markKeyForDeletation(record[pathColumnName]);
186
188
  }
187
189
  catch (e) {
188
190
  // file might be e.g. already deleted, so we catch error
@@ -206,7 +208,7 @@ export default class UploadPlugin extends AdminForthPlugin {
206
208
  if (oldRecord[pathColumnName]) {
207
209
  // put tag to delete old file
208
210
  try {
209
- yield this.options.storage.adapter.markKeyForDeletation(oldRecord[pathColumnName]);
211
+ yield this.options.storageAdapter.markKeyForDeletation(oldRecord[pathColumnName]);
210
212
  }
211
213
  catch (e) {
212
214
  // file might be e.g. already deleted, so we catch error
@@ -216,7 +218,7 @@ export default class UploadPlugin extends AdminForthPlugin {
216
218
  if (updates[virtualColumn.name] !== null) {
217
219
  // remove tag from new file
218
220
  // in this case we let it crash if it fails: this is a new file which just was uploaded.
219
- yield this.options.storage.adapter.markKeyForNotDeletation(updates[pathColumnName]);
221
+ yield this.options.storageAdapter.markKeyForNotDeletation(updates[pathColumnName]);
220
222
  }
221
223
  }
222
224
  return { ok: true };
@@ -261,13 +263,13 @@ export default class UploadPlugin extends AdminForthPlugin {
261
263
  if (filePath.startsWith('/')) {
262
264
  throw new Error('s3Path should not start with /, please adjust s3path function to not return / at the start of the path');
263
265
  }
264
- const { uploadUrl, uploadExtraParams } = yield this.options.storage.adapter.getUploadSignedUrl(filePath, contentType, 1800);
266
+ const { uploadUrl, uploadExtraParams } = yield this.options.storageAdapter.getUploadSignedUrl(filePath, contentType, 1800);
265
267
  let previewUrl;
266
268
  if ((_c = this.options.preview) === null || _c === void 0 ? void 0 : _c.previewUrl) {
267
269
  previewUrl = this.options.preview.previewUrl({ filePath });
268
270
  }
269
271
  else {
270
- previewUrl = yield this.options.storage.adapter.getDownloadUrl(filePath, 1800);
272
+ previewUrl = yield this.options.storageAdapter.getDownloadUrl(filePath, 1800);
271
273
  }
272
274
  return {
273
275
  uploadUrl,
@@ -316,7 +318,7 @@ export default class UploadPlugin extends AdminForthPlugin {
316
318
  if (!record) {
317
319
  return { error: `Record with id ${recordId} not found` };
318
320
  }
319
- attachmentFiles = this.options.generation.attachFiles({ record, adminUser });
321
+ attachmentFiles = yield this.options.generation.attachFiles({ record, adminUser });
320
322
  // if files is not array, make it array
321
323
  if (!Array.isArray(attachmentFiles)) {
322
324
  attachmentFiles = [attachmentFiles];
package/index.ts CHANGED
@@ -14,6 +14,8 @@ export default class UploadPlugin extends AdminForthPlugin {
14
14
  totalCalls: number;
15
15
  totalDuration: number;
16
16
 
17
+ resourceConfig: AdminForthResource;
18
+
17
19
  constructor(options: PluginOptions) {
18
20
  super(options, import.meta.url);
19
21
  this.options = options;
@@ -28,7 +30,8 @@ export default class UploadPlugin extends AdminForthPlugin {
28
30
  }
29
31
 
30
32
  async setupLifecycleRule() {
31
- this.options.storage.adapter.setupLifecycle();
33
+ const adapterUserUniqueRepresentation = `${this.resourceConfig.resourceId}-${this.pluginInstanceId}`;
34
+ this.options.storageAdapter.setupLifecycle(adapterUserUniqueRepresentation);
32
35
  }
33
36
 
34
37
  async genPreviewUrl(record: any) {
@@ -36,13 +39,14 @@ export default class UploadPlugin extends AdminForthPlugin {
36
39
  record[`previewUrl_${this.pluginInstanceId}`] = this.options.preview.previewUrl({ filePath: record[this.options.pathColumnName] });
37
40
  return;
38
41
  }
39
- const previewUrl = await this.options.storage.adapter.getDownloadUrl(record[this.options.pathColumnName], 1800);
42
+ const previewUrl = await this.options.storageAdapter.getDownloadUrl(record[this.options.pathColumnName], 1800);
40
43
 
41
44
  record[`previewUrl_${this.pluginInstanceId}`] = previewUrl;
42
45
  }
43
46
 
44
47
  async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
45
48
  super.modifyResourceConfig(adminforth, resourceConfig);
49
+ this.resourceConfig = resourceConfig;
46
50
  // after column to store the path of the uploaded file, add new VirtualColumn,
47
51
  // show only in edit and create views
48
52
  // use component uploader.vue
@@ -161,7 +165,7 @@ export default class UploadPlugin extends AdminForthPlugin {
161
165
  if (record[pathColumnName]) {
162
166
  process.env.HEAVY_DEBUG && console.log('🪥🪥 remove ObjectTagging', record[pathColumnName]);
163
167
  // let it crash if it fails: this is a new file which just was uploaded.
164
- await this.options.storage.adapter.markKeyForNotDeletation(record[pathColumnName]);
168
+ await this.options.storageAdapter.markKeyForNotDeletation(record[pathColumnName]);
165
169
  }
166
170
  return { ok: true };
167
171
  });
@@ -204,7 +208,7 @@ export default class UploadPlugin extends AdminForthPlugin {
204
208
  resourceConfig.hooks.delete.afterSave.push(async ({ record }: { record: any }) => {
205
209
  if (record[pathColumnName]) {
206
210
  try {
207
- await this.options.storage.adapter.markKeyForDeletation(record[pathColumnName]);
211
+ await this.options.storageAdapter.markKeyForDeletation(record[pathColumnName]);
208
212
  } catch (e) {
209
213
  // file might be e.g. already deleted, so we catch error
210
214
  console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${record[pathColumnName]}. File will not be auto-cleaned up`, e);
@@ -233,7 +237,7 @@ export default class UploadPlugin extends AdminForthPlugin {
233
237
  if (oldRecord[pathColumnName]) {
234
238
  // put tag to delete old file
235
239
  try {
236
- await this.options.storage.adapter.markKeyForDeletation(oldRecord[pathColumnName]);
240
+ await this.options.storageAdapter.markKeyForDeletation(oldRecord[pathColumnName]);
237
241
  } catch (e) {
238
242
  // file might be e.g. already deleted, so we catch error
239
243
  console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${oldRecord[pathColumnName]}. File will not be auto-cleaned up`, e);
@@ -242,7 +246,7 @@ export default class UploadPlugin extends AdminForthPlugin {
242
246
  if (updates[virtualColumn.name] !== null) {
243
247
  // remove tag from new file
244
248
  // in this case we let it crash if it fails: this is a new file which just was uploaded.
245
- await this.options.storage.adapter.markKeyForNotDeletation(updates[pathColumnName]);
249
+ await this.options.storageAdapter.markKeyForNotDeletation(updates[pathColumnName]);
246
250
  }
247
251
  }
248
252
  return { ok: true };
@@ -296,12 +300,12 @@ export default class UploadPlugin extends AdminForthPlugin {
296
300
  if (filePath.startsWith('/')) {
297
301
  throw new Error('s3Path should not start with /, please adjust s3path function to not return / at the start of the path');
298
302
  }
299
- const { uploadUrl, uploadExtraParams } = await this.options.storage.adapter.getUploadSignedUrl(filePath, contentType, 1800);
303
+ const { uploadUrl, uploadExtraParams } = await this.options.storageAdapter.getUploadSignedUrl(filePath, contentType, 1800);
300
304
  let previewUrl;
301
305
  if (this.options.preview?.previewUrl) {
302
306
  previewUrl = this.options.preview.previewUrl({ filePath });
303
307
  } else {
304
- previewUrl = await this.options.storage.adapter.getDownloadUrl(filePath, 1800);
308
+ previewUrl = await this.options.storageAdapter.getDownloadUrl(filePath, 1800);
305
309
  }
306
310
 
307
311
  return {
@@ -361,7 +365,7 @@ export default class UploadPlugin extends AdminForthPlugin {
361
365
  return { error: `Record with id ${recordId} not found` };
362
366
  }
363
367
 
364
- attachmentFiles = this.options.generation.attachFiles({ record, adminUser });
368
+ attachmentFiles = await this.options.generation.attachFiles({ record, adminUser });
365
369
  // if files is not array, make it array
366
370
  if (!Array.isArray(attachmentFiles)) {
367
371
  attachmentFiles = [attachmentFiles];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/upload",
3
- "version": "1.5.0",
3
+ "version": "2.0.1",
4
4
  "description": "Plugin for uploading files for adminforth",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/types.ts CHANGED
@@ -131,7 +131,7 @@ export type PluginOptions = {
131
131
  attachFiles?: ({ record, adminUser }: {
132
132
  record: any,
133
133
  adminUser: AdminUser,
134
- }) => string[],
134
+ }) => string[] | Promise<string[]>,
135
135
 
136
136
 
137
137
  /**
@@ -155,12 +155,9 @@ export type PluginOptions = {
155
155
 
156
156
  }
157
157
 
158
- storage?: {
159
- /**
160
- * The adapter used to store the files.
161
- * For now only S3 adapter is supported.
162
- */
163
- adapter: StorageAdapter,
164
- }
165
-
158
+ /**
159
+ * The adapter used to store the files.
160
+ * For now only S3 adapter is supported.
161
+ */
162
+ storageAdapter: StorageAdapter,
166
163
  }