mizzkey/src/server/api/endpoints/drive/files/create.ts

54 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-05-25 11:41:49 +02:00
import * as fs from 'fs';
2018-07-07 12:19:00 +02:00
import $ from 'cafy'; import ID from '../../../../../misc/cafy-id';
2018-03-29 13:32:18 +02:00
import { validateFileName, pack } from '../../../../../models/drive-file';
2018-04-07 21:02:12 +02:00
import create from '../../../../../services/drive/add-file';
2018-06-18 02:54:53 +02:00
import { ILocalUser } from '../../../../../models/user';
2016-12-28 23:49:51 +01:00
/**
* Create a file
*/
2018-07-05 19:58:29 +02:00
export default async (file: any, params: any, user: ILocalUser): Promise<any> => {
2017-02-11 17:39:27 +01:00
if (file == null) {
throw 'file is required';
2017-02-11 17:39:27 +01:00
}
2016-12-28 23:49:51 +01:00
// Get 'name' parameter
let name = file.originalname;
if (name !== undefined && name !== null) {
name = name.trim();
if (name.length === 0) {
name = null;
} else if (name === 'blob') {
name = null;
} else if (!validateFileName(name)) {
throw 'invalid name';
2016-12-28 23:49:51 +01:00
}
} else {
name = null;
}
2018-03-29 07:48:47 +02:00
// Get 'folderId' parameter
2018-07-05 16:36:07 +02:00
const [folderId = null, folderIdErr] = $.type(ID).optional.nullable.get(params.folderId);
2018-03-29 07:48:47 +02:00
if (folderIdErr) throw 'invalid folderId param';
2016-12-28 23:49:51 +01:00
2018-05-25 11:41:49 +02:00
function cleanup() {
fs.unlink(file.path, () => {});
}
2017-12-11 05:33:33 +01:00
try {
// Create file
const driveFile = await create(user, file.path, name, null, folderId);
2016-12-28 23:49:51 +01:00
2018-05-25 11:41:49 +02:00
cleanup();
2017-12-11 05:33:33 +01:00
// Serialize
2018-02-02 00:21:30 +01:00
return pack(driveFile);
2017-12-11 05:33:33 +01:00
} catch (e) {
console.error(e);
2018-05-25 11:41:49 +02:00
cleanup();
2017-12-11 05:33:33 +01:00
throw e;
}
};