Skip to content

Commit

Permalink
fix: filename option type (#249)
Browse files Browse the repository at this point in the history
* chore: eslint type-checking

* fix: filename option type

* chore: update typings
  • Loading branch information
kukhariev authored Jun 2, 2020
1 parent e64cfd8 commit 64ece4c
Show file tree
Hide file tree
Showing 18 changed files with 67 additions and 58 deletions.
6 changes: 4 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ module.exports = {
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
project: './tsconfig.eslint.json'
tsconfigRootDir: __dirname,
project: ['./tsconfig.eslint.json'],
warnOnUnsupportedTypeScriptVersion: false
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/eslint-recommended',
// 'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:promise/recommended',
'plugin:prettier/recommended',
'prettier',
Expand Down
4 changes: 2 additions & 2 deletions examples/express-gcs.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as express from 'express';
import { uploadx, GCStorage } from '../src';
import { GCStorage, uploadx } from '../src';

const app = express();

const storage = new GCStorage();

storage.onComplete = file => {
(file as any)['custom'] = 'Hi!';
file['custom'] = 'Hi!';
console.log('File upload complete: ', file);
};

Expand Down
6 changes: 3 additions & 3 deletions examples/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { DiskFile, DiskStorage, Multipart, OnComplete, Uploadx } from '../src';

const app = express();
const auth: express.Handler = (req, res, next) => {
(req as any).user = { id: '92be348f-172d-5f69-840d-100f79e4d1ef' };
req['user'] = { id: '92be348f-172d-5f69-840d-100f79e4d1ef' };
next();
};

Expand All @@ -14,10 +14,10 @@ const onComplete: OnComplete<DiskFile> = async file => {
const srcpath = `upload/${file.name}`;
const dstpath = `files/${file.originalName}`;
await promises.mkdir('files', { recursive: true });
promises.link(srcpath, dstpath);
await promises.link(srcpath, dstpath);
const message = `File upload is finished, path: ${dstpath}`;
console.log(message);
(file as any).message = message;
file['message'] = message;
};

const storage = new DiskStorage({
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"cleanup": "rimraf upload files dist",
"test": "jest",
"test:watch": "jest --watchAll",
"lint": "eslint \"{src,test,examples}/**/*.{ts,js}\" --fix",
"lint": "eslint \"{src,test}/**/*.ts\" --fix",
"demo:basic": "tsnd examples/express-basic",
"demo:express": "tsnd examples/express",
"demo:gcs": "tsnd -r dotenv/config examples/express-gcs",
Expand Down
8 changes: 7 additions & 1 deletion src/handlers/multipart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import { DiskStorage, DiskStorageOptions } from '../storages/disk-storage';
import { ERRORS, fail } from '../utils';
import { BaseHandler } from './base-handler';

interface MultipartyPart extends multiparty.Part {
headers: {
[key: string]: any;
'content-type': string;
};
}
export class Multipart<TFile extends Readonly<File>, L> extends BaseHandler {
storage: BaseStorage<TFile, L>;

Expand All @@ -26,7 +32,7 @@ export class Multipart<TFile extends Readonly<File>, L> extends BaseHandler {
Object.assign(config.metadata, key === 'metadata' ? JSON.parse(value) : { [key]: value });
});
form.on('error', error => reject(error));
form.on('part', (part: multiparty.Part) => {
form.on('part', (part: MultipartyPart) => {
config.size = part.byteCount;
config.originalName = part.filename;
config.contentType = part.headers['content-type'];
Expand Down
5 changes: 3 additions & 2 deletions src/storages/gcs-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type GCStorageOptions = BaseStorageOptions<GCSFile> &
*/
clientDirectUpload?: boolean;
};

export class GCSFile extends File {
GCSUploadURI?: string;
uri = '';
Expand All @@ -49,12 +50,12 @@ interface CGSObject {
name: string;
updated: Date;
}

/**
* Google cloud storage based backend.
*/
export class GCStorage extends BaseStorage<GCSFile, CGSObject> {
authClient: GoogleAuth;

storageBaseURI: string;
uploadBaseURI: string;

Expand Down Expand Up @@ -176,7 +177,7 @@ export class GCStorage extends BaseStorage<GCSFile, CGSObject> {
const message = await res.text();
return Promise.reject({ message, code: res.status });
} catch (error) {
this.log(uri, error.message);
this.log(uri, error);
return NaN;
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/storages/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface BaseStorageOptions<T> {
/** File size limit */
maxUploadSize?: number | string;
/** Filename generator function */
filename?: (file: Partial<File>) => string;
filename?: (file: File) => string;
useRelativeLocation?: boolean;
/** Completed callback */
onComplete?: OnComplete<T>;
Expand All @@ -24,7 +24,7 @@ export interface BaseStorageOptions<T> {
const defaultOptions: Required<BaseStorageOptions<any>> = {
allowMIME: ['*/*'],
maxUploadSize: '50GB',
filename: ({ userId, id }: Partial<File>): string => [userId, id].filter(Boolean).join('-'),
filename: ({ userId, id }: File): string => [userId, id].filter(Boolean).join('-'),
useRelativeLocation: false,
onComplete: () => undefined,
path: '/files'
Expand All @@ -38,7 +38,7 @@ export abstract class BaseStorage<TFile, TList> {
path: string;
isReady = false;
protected log = Logger.get(`store:${this.constructor.name}`);
protected namingFunction: (file: Partial<File>) => string;
protected namingFunction: (file: File) => string;
protected cache = new Cache<TFile>();

constructor(public config: BaseStorageOptions<TFile>) {
Expand Down
10 changes: 4 additions & 6 deletions test/base-handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
/* eslint-disable @typescript-eslint/unbound-method */
import { createRequest, createResponse } from 'node-mocks-http';
import { TestUploader } from './fixtures/uploader';

describe('BaseHandler', () => {
let uploader: TestUploader;
beforeEach(() => {
uploader = new TestUploader();
});
beforeEach(() => (uploader = new TestUploader()));

it('should implement get()', () => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
expect(uploader.get({ url: '/files/12345' } as any)).resolves.toEqual([]);
});

Expand All @@ -26,13 +24,12 @@ describe('BaseHandler', () => {
});

describe('sendError', () => {
let res: any;
beforeEach(() => {
uploader = new TestUploader();
res = createResponse();
});

it('should send Error (as string)', () => {
const res = createResponse();
const sendSpy = jest.spyOn(uploader, 'send');
const err = new Error('Error Message');
uploader.sendError(res, err);
Expand All @@ -45,6 +42,7 @@ describe('BaseHandler', () => {

it('should send Error (as json)', () => {
uploader.responseType = 'json';
const res = createResponse();
const sendSpy = jest.spyOn(uploader, 'send');
const err = new Error('Error Message');
uploader.sendError(res, err);
Expand Down
8 changes: 5 additions & 3 deletions test/fixtures/app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import * as express from 'express';
import { userPrefix } from '.';

interface ExtendedRequest extends express.Request {
[key: string]: any;
}
const app = express();
app.use((req, res, next) => {
(req as any).user = { id: userPrefix };
app.use((req: ExtendedRequest, res, next) => {
req['user'] = { id: userPrefix };
next();
});

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/gcs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
export const request = {
create: {
body: expect.any(String),
Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const userPrefix = 'userId';
export const root = 'files';

export const storageOptions: BaseStorageOptions<File> = {
filename: file => `${file.userId}/${file.originalName}`,
filename: file => `${file.userId || 'anonymous'}/${file.originalName}`,
maxUploadSize: '6GB',
allowMIME: ['video/*', 'image/*', 'application/octet-stream'],
useRelativeLocation: true
Expand Down
3 changes: 3 additions & 0 deletions test/gcs-storage.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { AbortSignal } from 'abort-controller';
import { createReadStream } from 'fs';
Expand Down
2 changes: 1 addition & 1 deletion test/multipart.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { join } from 'path';
import * as request from 'supertest';
import { multipart } from '../src/handlers/multipart';
Expand All @@ -16,7 +17,6 @@ describe('::Multipart', () => {

beforeAll(() => rimraf.sync(directory));
afterAll(() => rimraf.sync(directory));
beforeEach(() => (res = undefined as any));

test('wrapper', () => {
expect(multipart()).toBeInstanceOf(Function);
Expand Down
1 change: 1 addition & 0 deletions test/s3-storage.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { S3 } from 'aws-sdk';
import { createReadStream } from 'fs';
import { FilePart, S3File, S3Storage } from '../src';
Expand Down
15 changes: 7 additions & 8 deletions test/tus.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import * as fs from 'fs';
import { join } from 'path';
import * as request from 'supertest';
Expand All @@ -9,7 +10,6 @@ import { metadata, srcpath } from './fixtures/testfile';
import rimraf = require('rimraf');

describe('::Tus', () => {
let res: request.Response;
let uri: string;
const basePath = '/tus';
const directory = join(root, 'tus');
Expand All @@ -18,7 +18,6 @@ describe('::Tus', () => {

beforeAll(() => rimraf.sync(directory));
afterAll(() => rimraf.sync(directory));
afterEach(() => (res = undefined as any));

describe('express middleware', () => {
it('default storage', () => {
Expand All @@ -32,21 +31,21 @@ describe('::Tus', () => {

describe('POST', () => {
it('should 201', async () => {
res = await request(app)
const res = await request(app)
.post(basePath)
.set('Upload-Metadata', serializeMetadata(metadata))
.set('Upload-Length', metadata.size.toString())
.set('Tus-Resumable', TUS_RESUMABLE)
.expect(201)
.expect('tus-resumable', TUS_RESUMABLE);
uri = res.header.location;
uri = res.header.location as string;
expect(res.header.location).toEqual(expect.stringContaining('/tus'));
});
});

describe('PATCH', () => {
it('should 204 and Upload-Offset', async () => {
res = await request(app)
await request(app)
.patch(uri)
.set('Content-Type', 'application/offset+octet-stream')
.set('Upload-Offset', '0')
Expand All @@ -57,7 +56,7 @@ describe('::Tus', () => {
});

it('should 204', async () => {
res = await request(app)
await request(app)
.patch(uri)
.set('Content-Type', 'application/offset+octet-stream')
.set('Upload-Metadata', serializeMetadata(metadata))
Expand Down Expand Up @@ -112,7 +111,7 @@ describe('::Tus', () => {

describe('POST (creation-with-upload)', () => {
it('should return upload-offset', async () => {
res = await request(app)
const res = await request(app)
.post(basePath)
.set('Content-Type', 'application/offset+octet-stream')
.set('Upload-Metadata', serializeMetadata(metadata))
Expand All @@ -122,7 +121,7 @@ describe('::Tus', () => {
.expect(200)
.expect('tus-resumable', TUS_RESUMABLE)
.expect('upload-offset', '5');
uri = res.header.location;
uri = res.header.location as string;
expect(res.header.location).toEqual(expect.stringContaining('/tus'));
});
});
Expand Down
Loading

0 comments on commit 64ece4c

Please sign in to comment.