Skip to content

Commit

Permalink
chore(typescript): Migrate @feathersjs/express to TypeScript (#2152)
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl committed Dec 14, 2020
1 parent f99a380 commit 77bbffe
Show file tree
Hide file tree
Showing 25 changed files with 975 additions and 1,004 deletions.
16 changes: 1 addition & 15 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,4 @@ dist/
.mocha-puppeteer

# TypeScript compiled files
packages/adapter-commons/lib
packages/adapter-tests/lib
packages/authentication/lib
packages/authentication-local/lib
packages/authentication-client/lib
packages/authentication-oauth/lib
packages/configuration/lib
packages/commons/lib
packages/errors/lib
packages/feathers/lib
packages/tests/lib
packages/transport-commons/lib
packages/rest-client/lib
packages/socketio-client/lib
packages/socketio/lib
packages/**/lib
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import feathers, { Application as FeathersApplication } from '@feathersjs/feathers';
import express from '@feathersjs/express';
import * as express from '@feathersjs/express';
import rest from '@feathersjs/rest-client';

import authClient from '../../src';
Expand All @@ -15,7 +15,7 @@ describe('@feathersjs/authentication-client Express integration', () => {
const restApp = express.default(feathers())
.use(express.json())
.configure(express.rest())
.use(express.parseAuthentication('jwt'));
.use(express.parseAuthentication());
app = getApp(restApp as unknown as FeathersApplication) as express.Application;
app.use(express.errorHandler());

Expand Down
6 changes: 3 additions & 3 deletions packages/authentication-oauth/test/fixture.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import feathers, { Params } from '@feathersjs/feathers';
import express from '@feathersjs/express';
import express, { rest, errorHandler } from '@feathersjs/express';
import memory from 'feathers-memory';
import { AuthenticationService, JWTStrategy, AuthenticationRequest } from '@feathersjs/authentication';
import { express as oauth, OAuthStrategy } from '../src';
Expand All @@ -25,7 +25,7 @@ const auth = new AuthenticationService(app);
auth.register('jwt', new JWTStrategy());
auth.register('test', new TestOAuthStrategy());

app.configure(express.rest());
app.configure(rest());
app.set('host', '127.0.0.1');
app.set('port', port);
app.set('authentication', {
Expand Down Expand Up @@ -56,4 +56,4 @@ app.use('/authentication', auth);
app.use('/users', memory());

app.configure(oauth());
app.use(express.errorHandler({ logger: null }));
app.use(errorHandler({ logger: null }));
2 changes: 1 addition & 1 deletion packages/client/test/fixture.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
const rest = require('@feathersjs/express/rest');
const { rest } = require('@feathersjs/express');
const memory = require('feathers-memory');

// eslint-disable-next-line no-extend-native
Expand Down
60 changes: 0 additions & 60 deletions packages/express/index.d.ts

This file was deleted.

9 changes: 0 additions & 9 deletions packages/express/lib/not-found-handler.js

This file was deleted.

15 changes: 10 additions & 5 deletions packages/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"version": "5.0.0-pre.0",
"homepage": "https://feathersjs.com",
"main": "lib/",
"types": "index.d.ts",
"keywords": [
"feathers",
"feathers-plugin"
Expand Down Expand Up @@ -36,11 +35,12 @@
"README.md",
"src/**",
"lib/**",
"*.d.ts",
"*.js"
"public/**"
],
"scripts": {
"test": "mocha --config ../../.mocharc.json"
"prepublish": "npm run compile",
"compile": "shx rm -rf lib/ && tsc",
"test": "mocha --config ../../.mocharc.ts.json --recursive test/**.test.ts test/**/*.test.ts"
},
"directories": {
"lib": "lib"
Expand All @@ -58,13 +58,18 @@
"uberproto": "^2.0.6"
},
"devDependencies": {
"@types/mocha": "^8.0.4",
"@types/node": "^14.14.10",
"@feathersjs/authentication": "^5.0.0-pre.0",
"@feathersjs/authentication-local": "^5.0.0-pre.0",
"@feathersjs/feathers": "^5.0.0-pre.0",
"@feathersjs/tests": "^5.0.0-pre.0",
"axios": "^0.21.0",
"lodash": "^4.17.20",
"mocha": "^8.2.1"
"mocha": "^8.2.1",
"shx": "^0.3.3",
"ts-node": "^9.1.0",
"typescript": "^4.1.2"
},
"gitHead": "e6b82b809c21da298501a12b82e72e166468994b"
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
1 change: 0 additions & 1 deletion packages/express/rest.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
const flatten = require('lodash/flatten');
const merge = require('lodash/merge');
const debug = require('debug')('@feathersjs/express/authentication');
import Debug from 'debug';
import { merge, flatten } from 'lodash';
import { NextFunction, RequestHandler } from 'express';

const normalizeStrategy = (_settings = [], ..._strategies) =>
const debug = Debug('@feathersjs/express/authentication');

type StrategyOptions = {
service?: string;
strategies: string[]
};

const normalizeStrategy = (_settings: string|StrategyOptions, ..._strategies: string[]) =>
typeof _settings === 'string'
? { strategies: flatten([ _settings, ..._strategies ]) }
: _settings;

exports.parseAuthentication = (settings = {}) => {
export function parseAuthentication (settings: any = {}): RequestHandler {
return function (req, res, next) {
const { app } = req;
const { app } = req as any;
const service = app.defaultAuthentication ? app.defaultAuthentication(settings.service) : null;

if (service === null) {
Expand All @@ -25,7 +32,7 @@ exports.parseAuthentication = (settings = {}) => {
}

service.parse(req, res, ...authStrategies)
.then(authentication => {
.then((authentication: any) => {
if (authentication) {
debug('Parsed authentication from HTTP header', authentication);
merge(req, {
Expand All @@ -39,21 +46,22 @@ exports.parseAuthentication = (settings = {}) => {
};
};

exports.authenticate = (...strategies) => {
const settings = normalizeStrategy(...strategies);
export function authenticate (_settings: string|StrategyOptions, ..._strategies: string[]) {
const settings = normalizeStrategy(_settings, ..._strategies);

if (!Array.isArray(settings.strategies) || settings.strategies.length === 0) {
throw new Error(`'authenticate' middleware requires at least one strategy name`);
}

return function (req, res, next) {
return (_req: Request, _res: Response, next: NextFunction) => {
const req = _req as any;
const { app, authentication } = req;
const service = app.defaultAuthentication(settings.service);

debug('Authenticating with Express middleware and strategies', settings.strategies);

service.authenticate(authentication, req.feathers, ...settings.strategies)
.then(authResult => {
.then((authResult: any) => {
debug('Merging request with', authResult);
merge(req, authResult);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
const errors = require('@feathersjs/errors');
const path = require('path');
import path from 'path';
import { NotFound, GeneralError } from '@feathersjs/errors';
import { Request, Response, NextFunction, ErrorRequestHandler, RequestHandler } from 'express';

const defaults = {
public: path.resolve(__dirname, 'public'),
public: path.resolve(__dirname, '..', 'public'),
logger: console
};
const defaultHtmlError = path.resolve(defaults.public, 'default.html');

module.exports = function (options = {}) {
options = Object.assign({}, defaults, options);
export function notFound ({ verbose = false } = {}): RequestHandler {
return function (req: Request, _res: Response, next: NextFunction) {
const { url } = req;
const message = `Page not found${verbose ? ': ' + url : ''}`;

next(new NotFound(message, { url }));
};
}

export type ErrorHandlerOptions = {
public?: string,
logger?: boolean|{ error?: (msg: any) => void, info?: (msg: any) => void },
html?: any,
json?: any
};

export function errorHandler (_options: ErrorHandlerOptions = {}): ErrorRequestHandler {
const options = Object.assign({}, defaults, _options);

if (typeof options.html === 'undefined') {
options.html = {
Expand Down Expand Up @@ -36,18 +53,18 @@ module.exports = function (options = {}) {
}

if (error.type !== 'FeathersError') {
let oldError = error;
error = oldError.errors ? new errors.GeneralError(oldError.message, {
const oldError = error;

error = oldError.errors ? new GeneralError(oldError.message, {
errors: oldError.errors
}) : new errors.GeneralError(oldError.message);
}) : new GeneralError(oldError.message);

if (oldError.stack) {
error.stack = oldError.stack;
}
}

const formatter = {};
const formatter: { [key: string]: any } = {};

// If the developer passed a custom function for ALL html errors
if (typeof options.html === 'function') {
Expand All @@ -72,7 +89,7 @@ module.exports = function (options = {}) {
if (typeof options.json === 'function') {
formatter['application/json'] = options.json;
} else {
let handler = options.json[error.code] || options.json.default;
const handler = options.json[error.code] || options.json.default;
// If the developer passed a custom function for individual json errors
if (typeof handler === 'function') {
formatter['application/json'] = handler;
Expand All @@ -83,7 +100,7 @@ module.exports = function (options = {}) {
}

formatter['application/json'] = function () {
let output = Object.assign({}, error.toJSON());
const output = Object.assign({}, error.toJSON());

if (process.env.NODE_ENV === 'production') {
delete output.stack;
Expand All @@ -110,4 +127,4 @@ module.exports = function (options = {}) {
formatter['application/json'](error, req, res, next);
}
};
};
}
Loading

0 comments on commit 77bbffe

Please sign in to comment.