1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-15 09:04:04 +02:00
joplin/packages/lib/services/rest/routes/resources.ts

45 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-11-05 18:58:23 +02:00
import BaseModel from '../../../BaseModel';
import shim from '../../../shim';
import { Request, RequestMethod } from '../Api';
import defaultAction from '../utils/defaultAction';
import { ErrorBadRequest, ErrorNotFound } from '../utils/errors';
import readonlyProperties from '../utils/readonlyProperties';
import ApiResponse from '../ApiResponse';
const Resource = require('../../../models/Resource');
export default async function(request:Request, id:string = null, link:string = null) {
// fieldName: "data"
// headers: Object
// originalFilename: "test.jpg"
// path: "C:\Users\Laurent\AppData\Local\Temp\BW77wkpP23iIGUstd0kDuXXC.jpg"
// size: 164394
if (request.method === 'GET') {
if (link === 'file') {
const resource = await Resource.load(id);
if (!resource) throw new ErrorNotFound();
const filePath = Resource.fullPath(resource);
const buffer = await shim.fsDriver().readFile(filePath, 'Buffer');
const response = new ApiResponse();
response.type = 'attachment';
response.body = buffer;
response.contentType = resource.mime;
response.attachmentFilename = Resource.friendlyFilename(resource);
return response;
}
if (link) throw new ErrorNotFound();
}
if (request.method === RequestMethod.POST) {
if (!request.files.length) throw new ErrorBadRequest('Resource cannot be created without a file');
const filePath = request.files[0].path;
const defaultProps = request.bodyJson(readonlyProperties('POST'));
return shim.createResourceFromPath(filePath, defaultProps, { userSideValidation: true });
}
return defaultAction(BaseModel.TYPE_RESOURCE, request, id, link);
}