@feathersjs/feathers 5.0.0-pre.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,348 @@
1
+ import {
2
+ EventEmitter, NextFunction, HookContext as BaseHookContext
3
+ } from './dependencies';
4
+
5
+ type SelfOrArray<S> = S | S[];
6
+ type OptionalPick<T, K extends PropertyKey> = Pick<T, Extract<keyof T, K>>
7
+
8
+ export type { NextFunction };
9
+
10
+ export interface Paginated<T> {
11
+ total: number;
12
+ limit: number;
13
+ skip: number;
14
+ data: T[];
15
+ }
16
+
17
+ export interface ServiceOptions {
18
+ events?: string[];
19
+ methods?: string[];
20
+ serviceEvents?: string[];
21
+ }
22
+
23
+ export interface ServiceMethods<T, D = Partial<T>> {
24
+ find (params?: Params): Promise<T | T[]>;
25
+
26
+ get (id: Id, params?: Params): Promise<T>;
27
+
28
+ create (data: D, params?: Params): Promise<T>;
29
+
30
+ update (id: NullableId, data: D, params?: Params): Promise<T | T[]>;
31
+
32
+ patch (id: NullableId, data: D, params?: Params): Promise<T | T[]>;
33
+
34
+ remove (id: NullableId, params?: Params): Promise<T | T[]>;
35
+
36
+ setup (app: Application, path: string): Promise<void>;
37
+ }
38
+
39
+ export interface ServiceOverloads<T, D> {
40
+ create? (data: D[], params?: Params): Promise<T[]>;
41
+
42
+ update? (id: Id, data: D, params?: Params): Promise<T>;
43
+
44
+ update? (id: null, data: D, params?: Params): Promise<T[]>;
45
+
46
+ patch? (id: Id, data: D, params?: Params): Promise<T>;
47
+
48
+ patch? (id: null, data: D, params?: Params): Promise<T[]>;
49
+
50
+ remove? (id: Id, params?: Params): Promise<T>;
51
+
52
+ remove? (id: null, params?: Params): Promise<T[]>;
53
+ }
54
+
55
+ export type Service<T, D = Partial<T>> =
56
+ ServiceMethods<T, D> &
57
+ ServiceOverloads<T, D>;
58
+
59
+ export type ServiceInterface<T, D = Partial<T>> =
60
+ Partial<ServiceMethods<T, D>>;
61
+
62
+ export interface ServiceAddons<A = Application, S = Service<any, any>> extends EventEmitter {
63
+ id?: string;
64
+ hooks (options: HookOptions<A, S>): this;
65
+ }
66
+
67
+ export interface ServiceHookOverloads<S> {
68
+ find (
69
+ params: Params,
70
+ context: HookContext
71
+ ): Promise<HookContext>;
72
+
73
+ get (
74
+ id: Id,
75
+ params: Params,
76
+ context: HookContext
77
+ ): Promise<HookContext>;
78
+
79
+ create (
80
+ data: ServiceGenericData<S> | ServiceGenericData<S>[],
81
+ params: Params,
82
+ context: HookContext
83
+ ): Promise<HookContext>;
84
+
85
+ update (
86
+ id: NullableId,
87
+ data: ServiceGenericData<S>,
88
+ params: Params,
89
+ context: HookContext
90
+ ): Promise<HookContext>;
91
+
92
+ patch (
93
+ id: NullableId,
94
+ data: ServiceGenericData<S>,
95
+ params: Params,
96
+ context: HookContext
97
+ ): Promise<HookContext>;
98
+
99
+ remove (
100
+ id: NullableId,
101
+ params: Params,
102
+ context: HookContext
103
+ ): Promise<HookContext>;
104
+ }
105
+
106
+ export type FeathersService<A = FeathersApplication, S = Service<any>> =
107
+ S & ServiceAddons<A, S> & OptionalPick<ServiceHookOverloads<S>, keyof S>;
108
+
109
+ export type CustomMethod<Methods extends string> = {
110
+ [k in Methods]: <X = any> (data: any, params?: Params) => Promise<X>;
111
+ }
112
+
113
+ export type ServiceMixin<A> = (service: FeathersService<A>, path: string, options?: ServiceOptions) => void;
114
+
115
+ export type ServiceGenericType<S> = S extends ServiceInterface<infer T> ? T : any;
116
+ export type ServiceGenericData<S> = S extends ServiceInterface<infer _T, infer D> ? D : any;
117
+
118
+ export interface FeathersApplication<ServiceTypes = any, AppSettings = any> {
119
+ /**
120
+ * The Feathers application version
121
+ */
122
+ version: string;
123
+
124
+ /**
125
+ * A list of callbacks that run when a new service is registered
126
+ */
127
+ mixins: ServiceMixin<Application<ServiceTypes, AppSettings>>[];
128
+
129
+ /**
130
+ * The index of all services keyed by their path.
131
+ *
132
+ * __Important:__ Services should always be retrieved via `app.service('name')`
133
+ * not via `app.services`.
134
+ */
135
+ services: ServiceTypes;
136
+
137
+ /**
138
+ * The application settings that can be used via
139
+ * `app.get` and `app.set`
140
+ */
141
+ settings: AppSettings;
142
+
143
+ /**
144
+ * A private-ish indicator if `app.setup()` has been called already
145
+ */
146
+ _isSetup: boolean;
147
+
148
+ /**
149
+ * Contains all registered application level hooks.
150
+ */
151
+ appHooks: HookMap<Application<ServiceTypes, AppSettings>, any>;
152
+
153
+ /**
154
+ * Retrieve an application setting by name
155
+ *
156
+ * @param name The setting name
157
+ */
158
+ get<L extends keyof AppSettings & string> (name: L): AppSettings[L];
159
+
160
+ /**
161
+ * Set an application setting
162
+ *
163
+ * @param name The setting name
164
+ * @param value The setting value
165
+ */
166
+ set<L extends keyof AppSettings & string> (name: L, value: AppSettings[L]): this;
167
+
168
+ /**
169
+ * Runs a callback configure function with the current application instance.
170
+ *
171
+ * @param callback The callback `(app: Application) => {}` to run
172
+ */
173
+ configure (callback: (this: this, app: this) => void): this;
174
+
175
+ /**
176
+ * Returns a fallback service instance that will be registered
177
+ * when no service was found. Usually throws a `NotFound` error
178
+ * but also used to instantiate client side services.
179
+ *
180
+ * @param location The path of the service
181
+ */
182
+ defaultService (location: string): ServiceInterface<any>;
183
+
184
+ /**
185
+ * Register a new service or a sub-app. When passed another
186
+ * Feathers application, all its services will be re-registered
187
+ * with the `path` prefix.
188
+ *
189
+ * @param path The path for the service to register
190
+ * @param service The service object to register or another
191
+ * Feathers application to use a sub-app under the `path` prefix.
192
+ * @param options The options for this service
193
+ */
194
+ use<L extends keyof ServiceTypes & string> (
195
+ path: L,
196
+ service: keyof any extends keyof ServiceTypes ? ServiceInterface<any> | Application : ServiceTypes[L],
197
+ options?: ServiceOptions
198
+ ): this;
199
+
200
+ /**
201
+ * Get the Feathers service instance for a path. This will
202
+ * be the service originally registered with Feathers functionality
203
+ * like hooks and events added.
204
+ *
205
+ * @param path The name of the service.
206
+ */
207
+ service<L extends keyof ServiceTypes & string> (
208
+ path: L
209
+ ): FeathersService<this, keyof any extends keyof ServiceTypes ? Service<any> : ServiceTypes[L]>;
210
+
211
+ setup (server?: any): Promise<this>;
212
+
213
+ /**
214
+ * Register application level hooks.
215
+ *
216
+ * @param map The application hook settings.
217
+ */
218
+ hooks (map: HookOptions<this, any>): this;
219
+ }
220
+
221
+ // This needs to be an interface instead of a type
222
+ // so that the declaration can be extended by other modules
223
+ export interface Application<ServiceTypes = any, AppSettings = any> extends FeathersApplication<ServiceTypes, AppSettings>, EventEmitter {
224
+
225
+ }
226
+
227
+ export type Id = number | string;
228
+ export type NullableId = Id | null;
229
+
230
+ export interface Query {
231
+ [key: string]: any;
232
+ }
233
+
234
+ export interface Params {
235
+ query?: Query;
236
+ provider?: string;
237
+ route?: { [key: string]: string };
238
+ headers?: { [key: string]: any };
239
+ [key: string]: any; // (JL) not sure if we want this
240
+ }
241
+
242
+ export interface HookContext<A = Application, S = any> extends BaseHookContext<ServiceGenericType<S>> {
243
+ /**
244
+ * A read only property that contains the Feathers application object. This can be used to
245
+ * retrieve other services (via context.app.service('name')) or configuration values.
246
+ */
247
+ readonly app: A;
248
+ /**
249
+ * A read only property with the name of the service method (one of find, get,
250
+ * create, update, patch, remove).
251
+ */
252
+ readonly method: string;
253
+ /**
254
+ * A read only property and contains the service name (or path) without leading or
255
+ * trailing slashes.
256
+ */
257
+ readonly path: string;
258
+ /**
259
+ * A read only property and contains the service this hook currently runs on.
260
+ */
261
+ readonly service: S;
262
+ /**
263
+ * A read only property with the hook type (one of before, after or error).
264
+ * Will be `null` for asynchronous hooks.
265
+ */
266
+ readonly type: null | 'before' | 'after' | 'error';
267
+ /**
268
+ * The list of method arguments. Should not be modified, modify the
269
+ * `params`, `data` and `id` properties instead.
270
+ */
271
+ readonly arguments: any[];
272
+ /**
273
+ * A writeable property containing the data of a create, update and patch service
274
+ * method call.
275
+ */
276
+ data?: ServiceGenericData<S>;
277
+ /**
278
+ * A writeable property with the error object that was thrown in a failed method call.
279
+ * It is only available in error hooks.
280
+ */
281
+ error?: any;
282
+ /**
283
+ * A writeable property and the id for a get, remove, update and patch service
284
+ * method call. For remove, update and patch context.id can also be null when
285
+ * modifying multiple entries. In all other cases it will be undefined.
286
+ */
287
+ id?: Id;
288
+ /**
289
+ * A writeable property that contains the service method parameters (including
290
+ * params.query).
291
+ */
292
+ params: Params;
293
+ /**
294
+ * A writeable property containing the result of the successful service method call.
295
+ * It is only available in after hooks.
296
+ *
297
+ * `context.result` can also be set in
298
+ *
299
+ * - A before hook to skip the actual service method (database) call
300
+ * - An error hook to swallow the error and return a result instead
301
+ */
302
+ result?: ServiceGenericType<S>;
303
+ /**
304
+ * A writeable, optional property and contains a 'safe' version of the data that
305
+ * should be sent to any client. If context.dispatch has not been set context.result
306
+ * will be sent to the client instead.
307
+ */
308
+ dispatch?: ServiceGenericType<S>;
309
+ /**
310
+ * A writeable, optional property that allows to override the standard HTTP status
311
+ * code that should be returned.
312
+ */
313
+ statusCode?: number;
314
+ /**
315
+ * The event emitted by this method. Can be set to `null` to skip event emitting.
316
+ */
317
+ event: string|null;
318
+ }
319
+
320
+ // Legacy hook typings
321
+ export type LegacyHookFunction<A = Application, S = Service<any, any>> =
322
+ (this: S, context: HookContext<A, S>) => (Promise<HookContext<Application, S> | void> | HookContext<Application, S> | void);
323
+
324
+ export type Hook<A = Application, S = Service<any, any>> = LegacyHookFunction<A, S>;
325
+
326
+ type LegacyHookMethodMap<A, S> =
327
+ { [L in keyof S]?: SelfOrArray<LegacyHookFunction<A, S>>; } &
328
+ { all?: SelfOrArray<LegacyHookFunction<A, S>> };
329
+
330
+ type LegacyHookTypeMap<A, S> =
331
+ SelfOrArray<LegacyHookFunction<A, S>> | LegacyHookMethodMap<A, S>;
332
+
333
+ export type LegacyHookMap<A, S> = {
334
+ before?: LegacyHookTypeMap<A, S>,
335
+ after?: LegacyHookTypeMap<A, S>,
336
+ error?: LegacyHookTypeMap<A, S>
337
+ }
338
+
339
+ // New @feathersjs/hook typings
340
+ export type HookFunction<A = Application, S = Service<any, any>> =
341
+ (context: HookContext<A, S>, next: NextFunction) => Promise<void>;
342
+
343
+ export type HookMap<A, S> = {
344
+ [L in keyof S]?: HookFunction<A, S>[];
345
+ };
346
+
347
+ export type HookOptions<A, S> =
348
+ HookMap<A, S> | HookFunction<A, S>[] | LegacyHookMap<A, S>;
@@ -0,0 +1,5 @@
1
+ import { EventEmitter } from 'events';
2
+ export * from '@feathersjs/commons';
3
+ export * from '@feathersjs/hooks';
4
+
5
+ export { EventEmitter };
package/src/events.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { NextFunction, EventEmitter } from './dependencies';
2
+ import { HookContext, FeathersService } from './declarations';
3
+ import { getServiceOptions, defaultEventMap } from './service';
4
+
5
+ export function eventHook (context: HookContext, next: NextFunction) {
6
+ const { events } = getServiceOptions((context as any).self);
7
+ const defaultEvent = (defaultEventMap as any)[context.method] || null;
8
+
9
+ context.event = defaultEvent;
10
+
11
+ return next().then(() => {
12
+ // Send the event only if the service does not do so already (indicated in the `events` option)
13
+ // This is used for custom events and for client services receiving event from the server
14
+ if (typeof context.event === 'string' && !events.includes(context.event)) {
15
+ const results = Array.isArray(context.result) ? context.result : [ context.result ];
16
+
17
+ results.forEach(element => (context as any).self.emit(context.event, element, context));
18
+ }
19
+ });
20
+ }
21
+
22
+ export function eventMixin<A> (service: FeathersService<A>) {
23
+ const isEmitter = typeof service.on === 'function' &&
24
+ typeof service.emit === 'function';
25
+
26
+ if (!isEmitter) {
27
+ Object.assign(service, EventEmitter.prototype);
28
+ }
29
+
30
+ return service;
31
+ }
@@ -0,0 +1,109 @@
1
+ import {
2
+ getManager, HookContextData, HookManager, HookMap, HOOKS, hooks, Middleware
3
+ } from '../dependencies';
4
+ import {
5
+ Service, ServiceOptions, HookContext, FeathersService, Application
6
+ } from '../declarations';
7
+ import { defaultServiceArguments, getHookMethods } from '../service';
8
+ import {
9
+ collectLegacyHooks,
10
+ enableLegacyHooks,
11
+ fromAfterHook,
12
+ fromBeforeHook,
13
+ fromErrorHooks
14
+ } from './legacy';
15
+
16
+ export { fromAfterHook, fromBeforeHook, fromErrorHooks };
17
+
18
+ export function createContext (service: Service<any>, method: string, data: HookContextData = {}) {
19
+ const createContext = (service as any)[method].createContext;
20
+
21
+ if (typeof createContext !== 'function') {
22
+ throw new Error(`Can not create context for method ${method}`);
23
+ }
24
+
25
+ return createContext(data) as HookContext;
26
+ }
27
+
28
+ export class FeathersHookManager<A> extends HookManager {
29
+ constructor (public app: A, public method: string) {
30
+ super();
31
+ this._middleware = [];
32
+ }
33
+
34
+ collectMiddleware (self: any, args: any[]): Middleware[] {
35
+ const app = this.app as any as Application;
36
+ const appHooks = app.appHooks[HOOKS].concat(app.appHooks[this.method] || []);
37
+ const legacyAppHooks = collectLegacyHooks(this.app, this.method);
38
+ const middleware = super.collectMiddleware(self, args);
39
+ const legacyHooks = collectLegacyHooks(self, this.method);
40
+
41
+ return [...appHooks, ...legacyAppHooks, ...middleware, ...legacyHooks];
42
+ }
43
+
44
+ initializeContext (self: any, args: any[], context: HookContext) {
45
+ const ctx = super.initializeContext(self, args, context);
46
+
47
+ ctx.params = ctx.params || {};
48
+
49
+ return ctx;
50
+ }
51
+
52
+ middleware (mw: Middleware[]) {
53
+ this._middleware.push(...mw);
54
+ return this;
55
+ }
56
+ }
57
+
58
+ export function hookMixin<A> (
59
+ this: A, service: FeathersService<A>, path: string, options: ServiceOptions
60
+ ) {
61
+ if (typeof service.hooks === 'function') {
62
+ return service;
63
+ }
64
+
65
+ const app = this;
66
+ const serviceMethodHooks = getHookMethods(service, options).reduce((res, method) => {
67
+ const params = (defaultServiceArguments as any)[method] || [ 'data', 'params' ];
68
+
69
+ res[method] = new FeathersHookManager<A>(app, method)
70
+ .params(...params)
71
+ .props({
72
+ app,
73
+ path,
74
+ method,
75
+ service,
76
+ event: null,
77
+ type: null
78
+ });
79
+
80
+ return res;
81
+ }, {} as HookMap);
82
+ const handleLegacyHooks = enableLegacyHooks(service);
83
+
84
+ hooks(service, serviceMethodHooks);
85
+
86
+ service.hooks = function (this: any, hookOptions: any) {
87
+ if (hookOptions.before || hookOptions.after || hookOptions.error) {
88
+ return handleLegacyHooks.call(this, hookOptions);
89
+ }
90
+
91
+ if (Array.isArray(hookOptions)) {
92
+ return hooks(this, hookOptions);
93
+ }
94
+
95
+ Object.keys(hookOptions).forEach(method => {
96
+ const manager = getManager(this[method]);
97
+
98
+ if (!(manager instanceof FeathersHookManager)) {
99
+ throw new Error(`Method ${method} is not a Feathers hooks enabled service method`);
100
+ }
101
+
102
+ manager.middleware(hookOptions[method]);
103
+ });
104
+
105
+ return this;
106
+ }
107
+
108
+ return service;
109
+ }
@@ -0,0 +1,138 @@
1
+ import { _ } from '../dependencies';
2
+ import { LegacyHookFunction } from '../declarations';
3
+
4
+ const { each } = _;
5
+
6
+ export function fromBeforeHook (hook: LegacyHookFunction) {
7
+ return (context: any, next: any) => {
8
+ context.type = 'before';
9
+
10
+ return Promise.resolve(hook.call(context.self, context)).then(() => {
11
+ context.type = null;
12
+ return next();
13
+ });
14
+ };
15
+ }
16
+
17
+ export function fromAfterHook (hook: LegacyHookFunction) {
18
+ return (context: any, next: any) => {
19
+ return next().then(() => {
20
+ context.type = 'after';
21
+ return hook.call(context.self, context)
22
+ }).then(() => {
23
+ context.type = null;
24
+ });
25
+ }
26
+ }
27
+
28
+ export function fromErrorHooks (hooks: LegacyHookFunction[]) {
29
+ return (context: any, next: any) => {
30
+ return next().catch((error: any) => {
31
+ let promise: Promise<any> = Promise.resolve();
32
+
33
+ context.original = { ...context };
34
+ context.error = error;
35
+ context.type = 'error';
36
+
37
+ delete context.result;
38
+
39
+ for (const hook of hooks) {
40
+ promise = promise.then(() => hook.call(context.self, context))
41
+ }
42
+
43
+ return promise.then(() => {
44
+ context.type = null;
45
+
46
+ if (context.result === undefined) {
47
+ throw context.error;
48
+ }
49
+ });
50
+ });
51
+ }
52
+ }
53
+
54
+ export function collectLegacyHooks (target: any, method: string) {
55
+ const {
56
+ before: { [method]: before = [] },
57
+ after: { [method]: after = [] },
58
+ error: { [method]: error = [] }
59
+ } = target.__hooks;
60
+ const beforeHooks = before;
61
+ const afterHooks = [...after].reverse();
62
+ const errorHook = fromErrorHooks(error);
63
+
64
+ return [errorHook, ...beforeHooks, ...afterHooks];
65
+ }
66
+
67
+ // Converts different hook registration formats into the
68
+ // same internal format
69
+ export function convertHookData (obj: any) {
70
+ let hook: any = {};
71
+
72
+ if (Array.isArray(obj)) {
73
+ hook = { all: obj };
74
+ } else if (typeof obj !== 'object') {
75
+ hook = { all: [ obj ] };
76
+ } else {
77
+ each(obj, function (value, key) {
78
+ hook[key] = !Array.isArray(value) ? [ value ] : value;
79
+ });
80
+ }
81
+
82
+ return hook;
83
+ }
84
+
85
+ // Add `.hooks` functionality to an object
86
+ export function enableLegacyHooks (
87
+ obj: any,
88
+ methods: string[] = ['find', 'get', 'create', 'update', 'patch', 'remove'],
89
+ types: string[] = ['before', 'after', 'error']
90
+ ) {
91
+ const hookData: any = {};
92
+
93
+ types.forEach(type => {
94
+ // Initialize properties where hook functions are stored
95
+ hookData[type] = {};
96
+ });
97
+
98
+ // Add non-enumerable `__hooks` property to the object
99
+ Object.defineProperty(obj, '__hooks', {
100
+ configurable: true,
101
+ value: hookData,
102
+ writable: true
103
+ });
104
+
105
+ return function legacyHooks (this: any, allHooks: any) {
106
+ each(allHooks, (current: any, type) => {
107
+ if (!this.__hooks[type]) {
108
+ throw new Error(`'${type}' is not a valid hook type`);
109
+ }
110
+
111
+ const hooks = convertHookData(current);
112
+
113
+ each(hooks, (_value, method) => {
114
+ if (method !== 'all' && methods.indexOf(method) === -1) {
115
+ throw new Error(`'${method}' is not a valid hook method`);
116
+ }
117
+ });
118
+
119
+ methods.forEach(method => {
120
+ let currentHooks = [...(hooks.all || []), ...(hooks[method] || [])];
121
+
122
+ this.__hooks[type][method] = this.__hooks[type][method] || [];
123
+
124
+ if (type === 'before') {
125
+ currentHooks = currentHooks.map(fromBeforeHook);
126
+ }
127
+
128
+ if (type === 'after') {
129
+ currentHooks = currentHooks.map(fromAfterHook);
130
+ }
131
+
132
+ this.__hooks[type][method].push(...currentHooks);
133
+ });
134
+ });
135
+
136
+ return this;
137
+ }
138
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { setDebug } from './dependencies';
2
+ import version from './version';
3
+ import { Feathers } from './application';
4
+ import { Application } from './declarations';
5
+
6
+ export function feathers<T = any, S = any> () {
7
+ return new Feathers<T, S>() as Application<T, S>;
8
+ }
9
+
10
+ feathers.setDebug = setDebug;
11
+
12
+ export { version, Feathers };
13
+ export * from './hooks/index';
14
+ export * from './declarations';
15
+ export * from './service';
16
+
17
+ if (typeof module !== 'undefined') {
18
+ module.exports = Object.assign(feathers, module.exports);
19
+ }