Skip to content
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

File Uploads #126

Merged
merged 37 commits into from
Sep 18, 2021
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
2672bfb
Using express-fileupload.
RobinTail Sep 12, 2021
d315860
Connecting multipart parser to createServer().
RobinTail Sep 12, 2021
df6c486
License: including express-fileupload.
RobinTail Sep 12, 2021
1a9397a
Example endpoint: fileUploadEndpoint.
RobinTail Sep 12, 2021
00d62e8
Test for the file upload.
RobinTail Sep 12, 2021
430bb2b
Introducing Endpoint::getInputMimeType() draft.
RobinTail Sep 13, 2021
8bff0e0
Ref: extracting createApiResponse() from helpers.
RobinTail Sep 13, 2021
57d6022
Ref: extracting mime.
RobinTail Sep 13, 2021
197699f
Feat: getInputMimeType() -> getInputMimeTypes().
RobinTail Sep 13, 2021
91f11e2
Feat: moving mimeTypes param to factory::build().
RobinTail Sep 13, 2021
59b0b7f
Introducing mimeUpload const.
RobinTail Sep 13, 2021
3321b3e
Introducing factory::build() option: type=json|upload.
RobinTail Sep 13, 2021
ffd9523
Removing todo.
RobinTail Sep 13, 2021
dbeaf8e
Mergin the latest changes from master (ts, mime).
RobinTail Sep 16, 2021
cbf2303
Minor code style fix.
RobinTail Sep 16, 2021
065f8e9
Introducing ZodUpload. No middleware, just input.
RobinTail Sep 18, 2021
4ade5d0
DNRY: Moving ErrMessage and errToObj to helpers.
RobinTail Sep 18, 2021
04af7c8
z.upload() is a single file.
RobinTail Sep 18, 2021
9d015c5
Ref: minor naming.
RobinTail Sep 18, 2021
9b3b783
Minor: todo.
RobinTail Sep 18, 2021
ee8e110
Ref: minor naming.
RobinTail Sep 18, 2021
9d0bf35
Config: server/upload.
RobinTail Sep 18, 2021
a9d1adc
Checking for files within request when calling getInitialInput().
RobinTail Sep 18, 2021
576d6d3
Ref: naming: mimeMultipart.
RobinTail Sep 18, 2021
d3e17ed
Removing todo.
RobinTail Sep 18, 2021
fe41e54
Ref: parsers usage in server.ts.
RobinTail Sep 18, 2021
8a26b92
Removing excessive import in test.
RobinTail Sep 18, 2021
eb150c4
Testing other params along with upload.
RobinTail Sep 18, 2021
24e15f8
ZodUpload tests.
RobinTail Sep 18, 2021
de0f4c3
Example: including the mime type refinement into the endpoint example.
RobinTail Sep 18, 2021
4623ae8
Changelog: future version 2.5.0.
RobinTail Sep 18, 2021
c62ed1a
Changelog: additional notes.
RobinTail Sep 18, 2021
74a5e90
Changelog: more options.
RobinTail Sep 18, 2021
8a5315d
Changelog: more info.
RobinTail Sep 18, 2021
ca95c46
Readme: the feature documentation and example.
RobinTail Sep 18, 2021
17c3e59
Merge branch 'master' into uploads
RobinTail Sep 18, 2021
05cff3f
Readme: additional note.
RobinTail Sep 18, 2021
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
26 changes: 26 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,29 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.



Express-FileUpload - https://github.com/richardgirges/express-fileupload

The MIT License (MIT)

Copyright (c) 2015 Richard Girges

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion coverage.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 71 additions & 0 deletions example/example.swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,77 @@ paths:
type: string
pattern: /\d+/
description: GET /v1/stream parameter
/v1/upload:
post:
responses:
"200":
description: POST /v1/upload Successful response
content:
application/json:
schema:
type: object
properties:
status:
type: string
enum:
- success
data:
type: object
properties:
name:
type: string
size:
type: integer
format: int64
minimum: 0
exclusiveMinimum: false
maximum: 9007199254740991
exclusiveMaximum: false
mime:
type: string
hash:
type: string
required:
- name
- size
- mime
- hash
required:
- status
- data
"400":
description: POST /v1/upload Error response
content:
application/json:
schema:
type: object
properties:
status:
type: string
enum:
- error
error:
type: object
properties:
message:
type: string
required:
- message
required:
- status
- error
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
avatar:
nullable: true
type: string
format: binary
RobinTail marked this conversation as resolved.
Show resolved Hide resolved
required: []
description: POST /v1/upload request body
components:
schemas: {}
responses: {}
Expand Down
24 changes: 24 additions & 0 deletions example/v1/file-upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {z, defaultEndpointsFactory} from '../../src';
import crypto from 'crypto';

export const fileUploadEndpoint = defaultEndpointsFactory.build({
method: 'post',
type: 'upload',
RobinTail marked this conversation as resolved.
Show resolved Hide resolved
input: z.object({
avatar: z.upload(),
}),
output: z.object({
name: z.string(),
size: z.number().int().nonnegative(),
mime: z.string(),
hash: z.string()
}),
handler: async ({input: {avatar}}) => {
return {
name: avatar.name,
size: avatar.size,
mime: avatar.mimetype,
hash: crypto.createHash('sha1').update(avatar.data).digest('hex')
};
}
});
12 changes: 8 additions & 4 deletions example/v1/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {DependsOnMethod, Routing} from '../../src';
import {fileUploadEndpoint} from './file-upload';
import {getUserEndpoint} from './get-user';
import {sendAvatar} from './send-avatar';
import {sendAvatarEndpoint} from './send-avatar';
import {setUserEndpoint} from './set-user';
import {streamAvatar} from './stream-avatar';
import {streamAvatarEndpoint} from './stream-avatar';

export const v1Routing: Routing = {
// syntax 1: methods are defined within the endpoint
Expand All @@ -14,6 +15,9 @@ export const v1Routing: Routing = {
}),

// custom result handler examples with a file serving
avatar: sendAvatar,
stream: streamAvatar
avatar: sendAvatarEndpoint,
stream: streamAvatarEndpoint,
RobinTail marked this conversation as resolved.
Show resolved Hide resolved

// file upload
upload: fileUploadEndpoint,
};
2 changes: 1 addition & 1 deletion example/v1/send-avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { z } from '../../src';
import {fileDownloadEndpointsFactory} from '../factories';
import fs from 'fs';

export const sendAvatar = fileDownloadEndpointsFactory.build({
export const sendAvatarEndpoint = fileDownloadEndpointsFactory.build({
methods: ['get'],
input: z.object({
userId: z.string().regex(/\d+/).transform((str) => parseInt(str, 10))
Expand Down
2 changes: 1 addition & 1 deletion example/v1/stream-avatar.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {z} from '../../src';
import {fileStreamingEndpointsFactory} from '../factories';

export const streamAvatar = fileStreamingEndpointsFactory.build({
export const streamAvatarEndpoint = fileStreamingEndpointsFactory.build({
methods: ['get'],
input: z.object({
userId: z.string().regex(/\d+/).transform((str) => parseInt(str, 10))
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"types": "dist/index.d.ts",
"dependencies": {
"express": "^4.17.1",
"express-fileupload": "^1.2.1",
"http-errors": "^1.8.0",
"mime": "^2.5.2",
"openapi3-ts": "^2.0.1",
Expand All @@ -33,6 +34,7 @@
"devDependencies": {
"@tsconfig/node10": "^1.0.8",
"@types/express": "^4.17.11",
"@types/express-fileupload": "^1.1.7",
"@types/http-errors": "^1.8.0",
"@types/jest": "^27.0.1",
"@types/mime": "^2.0.3",
Expand Down
14 changes: 14 additions & 0 deletions src/api-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {z} from 'zod';
import {mimeJson, MimeParam} from './mime';

export type ApiResponse<A = z.ZodTypeAny> = {
schema: A;
mimeTypes: string[];
};

export const createApiResponse = <S extends z.ZodTypeAny>(schema: S, mimeTypes: MimeParam = mimeJson) => {
return {
schema,
mimeTypes: typeof mimeTypes === 'string' ? [mimeTypes] : mimeTypes,
} as ApiResponse<S>;
};
17 changes: 14 additions & 3 deletions src/endpoint.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {Request, Response} from 'express';
import {Logger} from 'winston';
import {z} from 'zod';
import {ApiResponse} from './api-response';
import {CommonConfig} from './config-type';
import {
ApiResponse,
combineEndpointAndMiddlewareInputSchemas,
getInitialInput,
IOSchema,
Expand All @@ -13,6 +13,7 @@ import {
} from './helpers';
import {Method, MethodsDefinition} from './method';
import {MiddlewareDefinition} from './middleware';
import {mimeUpload} from './mime';
import {ResultHandlerDefinition} from './result-handler';

export type Handler<IN, OUT, OPT> = (params: {
Expand Down Expand Up @@ -40,6 +41,7 @@ export abstract class AbstractEndpoint {
public abstract getOutputSchema(): IOSchema;
public abstract getPositiveResponseSchema(): z.ZodTypeAny;
public abstract getNegativeResponseSchema(): z.ZodTypeAny;
public abstract getInputMimeTypes(): string[];
public abstract getPositiveMimeTypes(): string[];
public abstract getNegativeMimeTypes(): string[];
}
Expand Down Expand Up @@ -69,6 +71,7 @@ type EndpointProps<
> = {
middlewares: MiddlewareDefinition<any, any, any>[];
inputSchema: IN;
mimeTypes: string[];
outputSchema: OUT;
handler: Handler<z.output<Merge<IN, mIN>>, z.input<OUT>, OPT>;
resultHandler: ResultHandlerDefinition<POS, NEG>;
Expand All @@ -83,16 +86,18 @@ export class Endpoint<
protected methods: M[] = [];
protected middlewares: MiddlewareDefinition<any, any, any>[] = [];
protected inputSchema: Merge<IN, mIN>; // combined with middlewares input
protected mimeTypes: string[];
protected outputSchema: OUT;
protected handler: Handler<z.output<Merge<IN, mIN>>, z.input<OUT>, OPT>
protected resultHandler: ResultHandlerDefinition<POS, NEG>;

constructor({
middlewares, inputSchema, outputSchema, handler, resultHandler, description, ...rest
middlewares, inputSchema, outputSchema, handler, resultHandler, description, mimeTypes, ...rest
}: EndpointProps<IN, OUT, mIN, OPT, M, POS, NEG>) {
super();
this.middlewares = middlewares;
this.inputSchema = combineEndpointAndMiddlewareInputSchemas<IN, mIN>(inputSchema, middlewares);
this.mimeTypes = mimeTypes;
this.outputSchema = outputSchema;
this.handler = handler;
this.resultHandler = resultHandler;
Expand Down Expand Up @@ -124,6 +129,10 @@ export class Endpoint<
return this.resultHandler.getNegativeResponse().schema;
}

public override getInputMimeTypes() {
return this.mimeTypes;
}

public override getPositiveMimeTypes() {
return this.resultHandler.getPositiveResponse(this.outputSchema).mimeTypes;
}
Expand Down Expand Up @@ -222,7 +231,9 @@ export class Endpoint<
if (request.method === 'OPTIONS') {
return response.end();
}
const initialInput = getInitialInput(request);
const contentType = request.header('content-type') || '';
const isUpload = contentType.substr(0, mimeUpload.length).toLowerCase() === mimeUpload;
const initialInput = getInitialInput(request, isUpload);
try {
const {input, options, isStreamClosed} = await this.#runMiddlewares({
input: {...initialInput}, // preserve the initial
Expand Down
8 changes: 6 additions & 2 deletions src/endpoints-factory.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import {z} from 'zod';
import {ApiResponse} from './api-response';
import {Endpoint, Handler} from './endpoint';
import {ApiResponse, FlatObject, IOSchema, Merge} from './helpers';
import {FlatObject, IOSchema, Merge} from './helpers';
import {Method, MethodsDefinition} from './method';
import {MiddlewareDefinition} from './middleware';
import {mimeJson, mimeUpload} from './mime';
import {defaultResultHandler, ResultHandlerDefinition} from './result-handler';

type BuildProps<IN extends IOSchema, OUT extends IOSchema, mIN, mOUT, M extends Method> = {
input: IN;
output: OUT;
handler: Handler<z.output<Merge<IN, mIN>>, z.input<OUT>, mOUT>;
description?: string;
type?: 'json' | 'upload';
RobinTail marked this conversation as resolved.
Show resolved Hide resolved
} & MethodsDefinition<M>;

/** mIN, mOUT - accumulated from all middlewares */
Expand Down Expand Up @@ -39,14 +42,15 @@ export class EndpointsFactory<mIN, mOUT, POS extends ApiResponse, NEG extends Ap
}

public build<IN extends IOSchema, OUT extends IOSchema, M extends Method>({
input, output, handler, description, ...rest
input, output, handler, description, type, ...rest
}: BuildProps<IN, OUT, mIN, mOUT, M>) {
return new Endpoint<IN, OUT, mIN, mOUT, M, POS, NEG>({
handler, description,
middlewares: this.middlewares,
inputSchema: input,
outputSchema: output,
resultHandler: this.resultHandler,
mimeTypes: type === 'upload' ? [mimeUpload] : [mimeJson],
...rest
});
}
Expand Down
2 changes: 2 additions & 0 deletions src/extend-zod.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {ZodFile} from './file-schema';
import {ZodUpload} from './upload-schema';

export * from 'zod';
export const file = ZodFile.create;
export const upload = ZodUpload.create;
10 changes: 2 additions & 8 deletions src/file-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,12 @@ import {
ZodParsedType,
ZodType,
INVALID,
OK,
ZodString,
OK
} from 'zod';
import {ErrMessage, errToObj} from './helpers';

const zodFileKind = 'ZodFile';

// obtaining the private helper type from Zod
type ErrMessage = Exclude<Parameters<typeof ZodString.prototype.email>[0], undefined>;

// the copy of the private Zod errorUtil.errToObj
const errToObj = (message: ErrMessage | undefined) => typeof message === 'string' ? {message} : message || {};

declare type ZodFileCheck = {
kind: 'binary';
message?: string;
Expand Down
23 changes: 7 additions & 16 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {Request} from 'express';
import {HttpError} from 'http-errors';
import {getType} from 'mime';
import {z} from 'zod';
import {LoggerConfig, loggerLevels} from './config-type';
import {MiddlewareDefinition} from './middleware';
Expand Down Expand Up @@ -68,9 +67,10 @@ export function combineEndpointAndMiddlewareInputSchemas<IN extends IOSchema, mI
return extractObjectSchema(mSchema).merge(extractObjectSchema(input)) as Merge<IN, mIN>;
}

export function getInitialInput(request: Request): any {
export function getInitialInput(request: Request, isWithFiles: boolean): any {
switch (request.method) {
case 'POST':
return isWithFiles ? {...request.body, ...request.files} : request.body; // @todo configurable?
case 'PUT':
case 'PATCH':
return request.body;
Expand Down Expand Up @@ -107,17 +107,8 @@ export function getStatusCodeFromError(error: Error): number {
return 500;
}

export type ApiResponse<A = z.ZodTypeAny> = {
schema: A;
mimeTypes: string[];
};

export const createApiResponse = <S extends z.ZodTypeAny>(
schema: S,
mimeTypes: string | string[] = getType('json') || 'application/json'
) => {
return {
schema,
mimeTypes: typeof mimeTypes === 'string' ? [mimeTypes] : mimeTypes,
} as ApiResponse<S>;
};
// obtaining the private helper type from Zod
export type ErrMessage = Exclude<Parameters<typeof z.ZodString.prototype.email>[0], undefined>;

// the copy of the private Zod errorUtil.errToObj
export const errToObj = (message: ErrMessage | undefined) => typeof message === 'string' ? {message} : message || {};
Loading