Skip to content

Quick fix for adminjs-upload plugin #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 41 additions & 12 deletions src/buildRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,51 @@ import fromPairs from 'lodash/fromPairs.js';
import * as mime from 'mime-types';
import path from 'path';

import os from 'os';
import fs from 'fs';


import { WrongArgumentError } from './errors.js';
import { log } from './logger.js';

const INVALID_ADMIN_JS_INSTANCE =
'You have to pass an instance of AdminJS to the buildRouter() function';

const getFile = (fileField?: {
fieldname: string;
filename: string;
file: Record<string, unknown>;
}) => {
if (!fileField?.file) {
async function writeFile(path, data) {
return new Promise((resolve, reject) => {
fs.writeFile(path, data, (err) => {
if (err) {
reject(err);
}
else {
resolve(null);
}
});
});
}

const getFile = async (fileField) => {
if (fileField.type === 'file') {
fileField.name = fileField.filename;
const buffer = await fileField.toBuffer();
const tmpFilePath = path.join(os.tmpdir(), fileField.filename);
await writeFile(tmpFilePath, buffer);
return {
name: fileField.filename,
path: tmpFilePath
};
}
return null;
}
const { file, filename } = fileField;
file.name = filename;
return file;
};

//@ts-ignore
Array.prototype.asyncMap = async function (callback) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extending native prototypes is a bad practice, please create a helper method for this or simply use Promise.all

const result = [];
for (let index = 0; index < this.length; index++) {
//@ts-ignore
result.push(await callback(this[index], index, this));
}
return result;
};

export const buildRouter = async (
Expand Down Expand Up @@ -60,9 +88,10 @@ export const buildRouter = async (
{ value: string; file?: File }
>;
const fields = fromPairs(
Object.keys((body ?? {}) as Record<string, unknown>).map(key => [
//@ts-ignore
await Object.keys((body ?? {}) as Record<string, unknown>).asyncMap(async key => [
key,
getFile(body[key] as any) ?? body[key].value,
(await getFile(body[key] as any)) ?? body[key].value,
])
);
const html = await controller[route.action](
Expand Down