### Asynchronous App Setup Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/migrating.md Shows the change to an asynchronous app.setup() in v5, which now returns a Promise. ```javascript // Before app.setup() // Do something here // Now await app.setup() // Do something here ``` -------------------------------- ### Setup and Teardown Hooks Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/hooks.md Demonstrates how to use setup hooks to initialize a MongoDB connection and teardown hooks to close it. These hooks run once when the application starts or shuts down. ```typescript import { MongoClient } from 'mongodb' app.hooks({ setup: [ async (context: HookContext, next: NextFunction) => { // E.g. wait for MongoDB connection to complete await context.app.get('mongoClient').connect() await next() } ], teardown: [ async (context: HookContext, next: NextFunction) => { // Close MongoDB connection await context.app.get('mongoClient').close() await next() } ] }) ``` -------------------------------- ### Configure Application with Setup Function Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Use app.configure() to run a callback function for initializing plugins or separating application logic. This example shows how to set up a service. ```typescript const setupService = (app: Application) => { app.use('/todos', todoService) } app.configure(setupService) ``` -------------------------------- ### Server Setup with feathers-blob Source: https://github.com/feathersjs/feathers/blob/dove/docs/cookbook/express/file-uploading.md This snippet shows the server-side setup for a file upload service using feathers-blob and a filesystem storage adapter. Ensure the 'uploads' directory exists before starting the server. ```javascript /* --- server.js --- */ const feathers = require('@feathersjs/feathers'); const express = require('@feathersjs/express'); const socketio = require('@feathersjs/socketio'); // feathers-blob service const blobService = require('feathers-blob'); // Here we initialize a FileSystem storage, // but you can use feathers-blob with any other // storage service like AWS or Google Drive. const fs = require('fs-blob-store'); const blobStorage = fs(__dirname + '/uploads'); // Feathers app const app = express(feathers()); // Parse HTTP JSON bodies app.use(express.json()); // Parse URL-encoded params app.use(express.urlencoded({ extended: true })); // Add REST API support app.use(express.rest()); // Configure Socket.io real-time APIs app.configure(socketio()); // Upload Service app.use('/uploads', blobService({Model: blobStorage})); // Register a nicer error handler than the default Express one app.use(express.errorHandler()); // Start the server app.listen(3030, function(){ console.log('Feathers app started at localhost:3030') }); ``` -------------------------------- ### Install Socket.io Client Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/socketio.md Install the necessary packages for the Socket.io client. ```bash npm install @feathersjs/socketio-client socket.io-client --save ``` -------------------------------- ### Install @feathersjs/knex Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/knex.md Install the Knex adapter using npm. ```bash npm install --save @feathersjs/knex ``` -------------------------------- ### Setup HTTPS Server with Feathers and Express Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/express.md Configure and start an HTTPS server for a Feathers application, ensuring app.setup() is called. ```typescript import https from 'https' import { app } from './app' const port = app.get('port') const server = https .createServer( { key: fs.readFileSync('privatekey.pem'), cert: fs.readFileSync('certificate.pem') }, app ) .listen(443) // Call app.setup to initialize all services and SocketIO app.setup(server) server.on('listening', () => logger.info('Feathers application started')) ``` -------------------------------- ### Install @feathersjs/socketio-client Source: https://github.com/feathersjs/feathers/blob/dove/packages/socketio-client/README.md Install the @feathersjs/socketio-client package using npm. ```bash npm install @feathersjs/socketio-client --save ``` -------------------------------- ### Initialize Application Settings and Start Server Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Demonstrates setting application-wide configuration values like the port and then starting the server using app.listen(). Settings can be typed during app initialization. ```typescript import { feathers } from '@feathersjs/feathers' type ServiceTypes = { // Add services path to type mapping here } // app.get and app.set can be typed when initializing the app type Configuration = { port: number } const app = feathers() app.set('port', 3030) app.listen(app.get('port')) ``` -------------------------------- ### Install Authentication Client Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/client.md Install the @feathersjs/authentication-client module using npm. ```bash npm install @feathersjs/authentication-client --save ``` -------------------------------- ### Install OAuth Package Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/oauth.md Install the @feathersjs/authentication-oauth package using npm. ```bash npm install @feathersjs/authentication-oauth --save ``` -------------------------------- ### Install @feathersjs/rest-client Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/rest.md Install the @feathersjs/rest-client package using npm. ```bash npm install @feathersjs/rest-client --save ``` -------------------------------- ### Install Socket.io Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/socketio.md Install the Socket.io module for FeathersJS using npm. ```bash npm install @feathersjs/socketio --save ``` -------------------------------- ### Install @feathersjs/configuration Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/configuration.md Install the configuration module using npm. ```bash npm install @feathersjs/configuration --save ``` -------------------------------- ### Client-Server Testing Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/cookbook/general/client-test.md This example demonstrates how to set up a Feathers client and run tests against a Feathers server. It includes setting up the server, creating a client, authenticating, and performing service operations. ```javascript const assert = require('assert'); const feathersClient = require('@feathersjs/client'); const io = require('socket.io-client'); const app = require('../../src/app'); const host = app.get('host'); const port = app.get('port'); const email = 'login@example.com'; const password = 'login'; describe('\'users\' service - client', function () { this.timeout(10000); let server; let client; before(async () => { await app.service('users').create({ email, password }); server = app.listen(port); server.on('listening', async () => { // eslint-disable-next-line no-console console.log('Feathers application started on http://%s:%d', host, port); }); client = await makeClient(host, port, email, password); }); after(() => { client.logout(); server.close(); }); describe('Run tests using client and server', () => { it('registered the service', () => { const service = client.service('users'); assert.ok(service, 'Registered the service'); }); it('creates a user, encrypts password and adds gravatar', async () => { const user = await client.service('users').create({ email: 'testclient@example.com', password: 'secret' }); // Verify Gravatar has been set to what we'd expect assert.equal(user.avatar, 'https://s.gravatar.com/avatar/1b9c869fa7a93e59463c31a377fe0cf6?s=60'); // Makes sure the password got encrypted assert.ok(user.password !== 'secret'); }); it('removes password for external requests', async () => { // Setting `provider` indicates an external request const params = { provider: 'rest' }; const user = await client.service('users').create({ email: 'testclient2@example.com', password: 'secret' }, params); // Make sure password has been removed assert.ok(!user.password); }); }); }); async function makeClient(host, port, email, password) { const client = feathersClient(); const socket = io(`http://${host}:${port}`, { transports: ['websocket'], forceNew: true, reconnection: false, extraHeaders: {} }); client.configure(feathersClient.socketio(socket)); client.configure(feathersClient.authentication({ storage: localStorage() })); await client.authenticate({ strategy: 'local', email, password, }); return client; } function localStorage () { const store = {}; return { setItem (key, value) { store[key] = value; }, getItem (key) { return store[key]; }, removeItem (key) { delete store[key]; } }; } ``` -------------------------------- ### Configure Feathers Client with Authentication Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/client.md Set up the Feathers client by configuring the transport (e.g., Socket.IO) and then the authentication client. This example shows basic setup with Socket.IO. ```typescript import { feathers } from '@feathersjs/feathers' import socketio from '@feathersjs/socketio-client' import io from 'socket.io-client' import authentication from '@feathersjs/authentication-client' const socket = io('http://api.feathersjs.com') const app = feathers() // Setup the transport (Rest, Socket, etc.) here app.configure(socketio(socket)) // Available options are listed in the "Options" section app.configure(authentication()) ``` -------------------------------- ### Initialize npm and Install TypeScript (TypeScript) Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/starting.md Initialize a new Node.js project and install TypeScript and related packages as development dependencies. Also initializes a TypeScript configuration file. ```sh npm init --yes # Install TypeScript and its NodeJS wrapper npm i typescript ts-node @types/node --save-dev # Also initialize a TS configuration file that uses modern JavaScript npx tsc --init --target es2020 ``` -------------------------------- ### Asynchronous App Listen Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/migrating.md Demonstrates the change from synchronous to asynchronous app.listen() in v5. ```javascript // Before const server = app.listen(3030) // Now app.listen(3030).then((server) => {}) ``` -------------------------------- ### Install Local Authentication Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/local.md Install the @feathersjs/authentication-local package using npm. ```bash npm install @feathersjs/authentication-local --save ``` -------------------------------- ### Install nyc for Code Coverage Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/testing.md Install the nyc command line tool as a development dependency. ```sh npm install nyc --save-dev ``` -------------------------------- ### Applying Method-Specific Hooks Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/hooks.md This example demonstrates how to apply specific hooks to individual service methods like 'find' and 'get', while using a general hook for all methods. This allows for more granular control over hook execution. ```typescript app.service('messages').hooks({ around: { all: [authenticate('jwt')], find: [logRuntime], get: [logRuntime] } // ... }) ``` -------------------------------- ### Install @feathersjs/typebox Source: https://github.com/feathersjs/feathers/blob/dove/packages/typebox/README.md Install the @feathersjs/typebox package using npm. ```bash npm install @feathersjs/typebox --save ``` -------------------------------- ### Registering Setup and Teardown Hooks Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/app.md This code demonstrates how to register hooks that execute once during application startup (setup) or shutdown (teardown), useful for dynamic configuration. ```typescript // Register application setup and teardown hooks here app.hooks({ setup: [], teardown: [] }) ``` -------------------------------- ### App-Level Setup and Teardown Hooks Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/whats-new.md Shows how to register app-level 'setup' and 'teardown' hooks for asynchronous logic during server startup and shutdown. These hooks run on the app level, not the service level. ```typescript app.hooks({ setup: [connectMongoDB], teardown: [closeMongoDB] }) ``` -------------------------------- ### Install MongoDB Adapter Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/mongodb.md Install the @feathersjs/mongodb package using npm. ```bash $ npm install --save @feathersjs/mongodb ``` -------------------------------- ### Install Feathers Core Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Install the core Feathers module using npm. ```bash npm install @feathersjs/feathers --save ``` -------------------------------- ### Install JWT Authentication Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/jwt.md Install the JWT authentication package using npm. ```bash npm install @feathersjs/authentication --save ``` -------------------------------- ### Install Memory Adapter Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/memory.md Install the @feathersjs/memory package using npm. ```bash npm install --save @feathersjs/memory ``` -------------------------------- ### Start Docker Container Source: https://github.com/feathersjs/feathers/blob/dove/docs/cookbook/deploy/docker.md Starts a Docker container from the 'my-feathers-image' and maps port 3030. ```sh docker run -d -p 3030:3030 --name my-feathers-container my-feathers-image ``` -------------------------------- ### Install Feathers Adapter Commons Source: https://github.com/feathersjs/feathers/blob/dove/packages/adapter-commons/README.md Install the @feathersjs/adapter-commons package using npm. ```bash npm install @feathersjs/adapter-commons --save ``` -------------------------------- ### Create Installable SDK Package Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/client.md Create an npm package for the Feathers client SDK. This package can be installed from a running server. ```bash npm run bundle:client ``` ```bash npm install https://myapp.com/appname-x.x.x.tgz ``` -------------------------------- ### OAuth Authentication Setup Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/oauth.md Configure the authentication service with JWT and OAuth strategies. This setup registers 'jwt', 'github', and 'google' strategies and configures the OAuth middleware. ```typescript import { AuthenticationService, JWTStrategy } from '@feathersjs/authentication' import { LocalStrategy } from '@feathersjs/authentication-local' import { OAuthStrategy, oauth } from '@feathersjs/authentication-oauth' import type { Application } from './declarations' declare module './declarations' { interface ServiceTypes { authentication: AuthenticationService } } export const authentication = (app: Application) => { const authentication = new AuthenticationService(app) authentication.register('jwt', new JWTStrategy()) authentication.register('github', new OAuthStrategy()) authentication.register('google', new OAuthStrategy()) app.use('authentication', authentication) app.configure(oauth({})) } ``` -------------------------------- ### Install dotenv for .env file support Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/custom-environment-variables.md Install the dotenv package to enable loading environment variables from a .env file. ```bash npm install dotenv --save ``` -------------------------------- ### MongoDB Atlas Connection String Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/databases.md Example of a MongoDB Atlas connection string for configuration. ```text mongodb+srv://:@cluster0.xyz.mongodb.net/?retryWrites=true&w=majority ``` -------------------------------- ### Install TypeScript Reporter for nyc Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/testing.md For TypeScript projects, install the nyc TypeScript reporter. ```sh npm install @istanbuljs/nyc-config-typescript --save-dev ``` -------------------------------- ### OAuth Configuration Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/oauth.md Example JSON configuration for OAuth authentication, specifying allowed origins, redirect paths, and credentials for Google and Twitter strategies. ```json { "authentication": { "origins": ["localhost:3030"], "oauth": { "redirect": "/frontend", "google": { "key": "...", "secret": "...", "custom_params": { "access_type": "offline" } }, "twitter": { "key": "...", "secret": "..." } } } } ``` -------------------------------- ### Install Feathers CLI Source: https://github.com/feathersjs/feathers/blob/dove/packages/cli/README.md Install the Feathers CLI as a development dependency using npm. ```bash npm install @feathersjs/cli --save-dev ``` -------------------------------- ### Standard Authentication Service Setup Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/service.md Initialize the AuthenticationService with JWT and Local strategies. This setup is typically used by the FeathersJS generator. ```typescript import { AuthenticationService, JWTStrategy } from '@feathersjs/authentication' import { LocalStrategy } from '@feathersjs/authentication-local' import type { Application } from './declarations' declare module './declarations' { interface ServiceTypes { authentication: AuthenticationService } } export const authentication = (app: Application) => { const authentication = new AuthenticationService(app) authentication.register('jwt', new JWTStrategy()) authentication.register('local', new LocalStrategy()) app.use('authentication', authentication) } ``` -------------------------------- ### Generate Authentication Setup Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/authentication.md Run this command to initialize a standard authentication setup in your Feathers.js application. This includes setting up user endpoints and authentication endpoints. ```bash npx feathers generate authentication ``` -------------------------------- ### Install Feathers Project Dependencies Source: https://github.com/feathersjs/feathers/blob/dove/README.md Clone the Feathers repository and install its dependencies to begin development. This is for contributing to the Feathers framework itself. ```bash cd feathers npm install ``` -------------------------------- ### Install Feathers Knex Adapter Source: https://github.com/feathersjs/feathers/blob/dove/packages/knex/README.md Install the Feathers Knex adapter using npm. This command adds the package as a project dependency. ```bash npm install @feathersjs/knex --save ``` -------------------------------- ### Setup Sub-App with Express Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/express.md Register a Feathers app as a sub-app within an Express app and explicitly call setup. ```typescript import { feathers } from '@feathersjs/feathers' import express from '@feathersjs/express' const api = feathers() api.use('service', myService) const mainApp = express(feathers()).use('/api/v1', api) const server = await mainApp.listen(3030) // Now call setup on the Feathers app with the server await api.setup(server) ``` -------------------------------- ### Local Authentication Configuration Example Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/local.md Example of how to configure the LocalStrategy options in Feathers configuration files (e.g., config/default.json). This specifies the username and password fields. ```json { "authentication": { "local": { "usernameField": "email", "passwordField": "password" } } } ``` -------------------------------- ### Install Feathers Socket.io, Koa, and Koa-Static Packages (JavaScript) Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/starting.md Install the necessary Feathers packages for Socket.io and KoaJS, along with koa-static for serving static files, when using JavaScript. Run this command in your project's root directory. ```sh npm install @feathersjs/socketio @feathersjs/koa koa-static --save ``` -------------------------------- ### .setup([server]) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Initializes all services by calling each service's .setup(app, path) method. It also sets up SocketIO (if enabled) and other providers requiring a server instance. This method returns a Promise that resolves with the application instance. ```APIDOC ## .setup([server]) `app.setup([server]) -> Promise` is used to initialize all services by calling each [services .setup(app, path)](services.md#setupapp-path) method (if available). It will also use the `server` instance passed (e.g. through `http.createServer`) to set up SocketIO (if enabled) and any other provider that might require the server instance. You can register [application setup hooks](./hooks.md#setup-and-teardown) to e.g. set up database connections and other things required to be initialized on startup in a certain order. Normally `app.setup` will be called automatically when starting the application via [app.listen([port])](#listen-port) but there are cases (like in tests) when it can be called explicitly. ``` -------------------------------- ### Find Messages with Text Starting with 'Hello' Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/knex.md Demonstrates how to use the $like operator to find records where a text field matches a pattern. This example finds messages starting with 'Hello'. ```typescript app.service('messages').find({ query: { text: { $like: 'Hello%' } } }) ``` -------------------------------- ### Find Messages with Case-Insensitive Text Starting with 'hello' Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/knex.md Shows how to use the $ilike operator (PostgreSQL specific) for case-insensitive pattern matching. This example finds messages starting with 'hello', ignoring case. ```typescript app.service('messages').find({ query: { text: { $ilike: 'hello%' } } }) ``` -------------------------------- ### .setup(app, path) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/services.md Initializes the service, passing the Feathers application instance and the path it's registered on. This method is called automatically during application setup. ```APIDOC ## .setup(app, path) ### Description Initializes the service, passing an instance of the Feathers application and the path it has been registered on. When calling [app.listen](application.md#listenport) or [app.setup](application.md#setupserver) all registered services `setup` methods will be called. If a service is registered afterwards, the `setup` method will be called immediately. ### Method `setup(app, path) -> Promise` ### Parameters #### Path Parameters - **app** (object) - The Feathers application instance. - **path** (string) - The path the service is registered on. ``` -------------------------------- ### .listen(port) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Starts the application on the given port, sets up configured transports, runs app.setup(server), and returns the server object. This method is only available if a server-side transport (REST or websocket) has been configured. ```APIDOC ## .listen(port) `app.listen([port]) -> Promise` starts the application on the given port. It will set up all configured transports (if any) and then run [app.setup(server)](#setup-server) with the server object and then return the server object. `listen` will only be available if a server side transport (REST or websocket) has been configured. ``` -------------------------------- ### Registering Method-Specific Hooks Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/service.md Adds specific hooks, like the profiler, to individual service methods (`find` and `get` in this example) by overriding the `around` configuration. ```typescript import { profiler } from '../../hooks/profiler' // ... // Initialize hooks app.service(messagePath).hooks({ around: { all: [ authenticate('jwt'), schemaHooks.resolveExternal(messageExternalResolver), schemaHooks.resolveResult(messageResolver) ], find: [profiler], get: [profiler] }, before: { all: [schemaHooks.validateQuery(messageQueryValidator), schemaHooks.resolveQuery(messageQueryResolver)], find: [], get: [], create: [schemaHooks.validateData(messageDataValidator), schemaHooks.resolveData(messageDataResolver)], patch: [schemaHooks.validateData(messagePatchValidator), schemaHooks.resolveData(messagePatchResolver)], remove: [] }, after: { all: [] }, error: { all: [] } }) ``` -------------------------------- ### Check Node.js Version Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/starting.md Verify that Node.js is installed by checking its version. ```sh node --version ``` -------------------------------- ### Find Resources with Special Query Parameters (HTTP) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/rest.md Example of passing special query parameters like $limit and $select via HTTP GET request. ```http GET /messages?status=read&$limit=10&$select[]=text ``` -------------------------------- ### Configuring Application Services Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/app.md Example of how to configure the main application by calling configure functions for authentication and services. The order of configuration can be important. ```typescript // ... import { services } from './services' // ... app.configure(authentication) app.configure(services) // ... ``` -------------------------------- ### Remove Connection from All Channels Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/channels.md This example demonstrates how to remove a connection from all channels when a user is removed. It uses `app.channel(app.channels)` to get a channel representing all connections and then uses the `leave` method with a filter function. ```typescript import type { RealTimeConnection } from '@feathersjs/feathers' // When a user is removed, make all their connections leave every channel app.service('users').on('removed', (user: User) => { app.channel(app.channels).leave((connection: RealTimeConnection) => { return user._id === connection.user._id }) }) ``` -------------------------------- ### Select Specific Fields in Query Results Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/databases/querying.md Use `$select` to specify which fields to include in the query results. This example selects only the `text` and `userId` fields for a `find` call and only `text` for a `get` call. ```javascript // Only return the `text` and `userId` field in a message app.service('messages').find({ query: { $select: ['text', 'userId'] } }) app.service('messages').get(1, { query: { $select: ['text'] } }) ``` ```http GET /messages?$select[]=text&$select[]=userId GET /messages/1?$select[]=text ``` -------------------------------- ### Navigate to App Directory Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/generator.md After generating the application, change into the newly created project directory to begin development. ```sh cd feathers-chat ``` -------------------------------- ### JWT Revocation using Redis Source: https://github.com/feathersjs/feathers/blob/dove/docs/cookbook/authentication/revoke-jwt.md This example shows how to revoke JWTs using Redis for storage. It leverages Redis's ability to set expiration times for keys, ensuring revoked tokens are automatically removed after they expire. This approach is more scalable and efficient for production environments. Ensure you have the 'redis' package installed. ```bash npm install redis ``` ```javascript const redis = require('redis'); const { AuthenticationService } = require('@feathersjs/authentication'); const { NotAuthenticated } = require('@feathersjs/errors'); class RedisAuthService extends AuthenticationService { constructor (app, configKey) { super(app, configKey); const client = redis.createClient(); this.redis = { client, get: client.get.bind(client), set: client.set.bind(client), exists: client.exists.bind(client), expireat: client.exists.bind(client) } (async () => { await this.redis.client.connect(); })() } async revokeAccessToken (accessToken) { // First make sure the access token is valid const verified = await this.verifyAccessToken(accessToken); // Calculate the remaining valid time for the token (in seconds) const expiry = verified.exp - Math.floor(Date.now() / 1000); // Add the revoked token to Redis and set expiration await this.redis.set(accessToken, 1, { EX: expiry }); return verified; } async verifyAccessToken(accessToken) { if (await this.redis.exists(accessToken)) { throw new NotAuthenticated('Token revoked'); } return super.verifyAccessToken(accessToken); } async remove (id, params) { const authResult = await super.remove(id, params); const { accessToken } = authResult; if (accessToken) { // If there is an access token, revoke it await this.revokeAccessToken(accessToken); } return authResult; } } app.use('/authentication', new RedisAuthService(app)); ``` -------------------------------- ### Implementing Feathers Services as Class or Object Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/services.md Demonstrates how to define a Feathers service using either a class or a plain JavaScript object. Both approaches must implement standard service methods like `find`, `get`, `create`, `update`, `patch`, and `remove`. The `setup` and `teardown` methods are also shown for lifecycle management. ```typescript import { feathers } from '@feathersjs/feathers' import type { Params, Id, NullableId } from '@feathersjs/feathers' class MyServiceClass { async find(params: Params) { return [] } async get(id: Id, params: Params) {} async create(data: any, params: Params) {} async update(id: NullableId, data: any, params: Params) {} async patch(id: NullableId, data: any, params: Params) {} async remove(id: NullableId, params: Params) {} async setup(app: Application, path: string) {} async teardown(app: Application, path: string) {} } const myServiceObject = { async find(params: Params) { return [] }, async get(id: Id, params: Params) {}, async create(data: any, params: Params) {}, async update(id: NullableId, data: any, params: Params) {}, async patch(id: NullableId, data: any, params: Params) {}, async remove(id: NullableId, params: Params) {}, async setup(app: Application, path: string) {} async teardown(app: Application, path: string) {} } type ServiceTypes = { 'my-service': MyServiceClass 'my-service-object': typeof myServiceObject } const app = feathers() app.use('my-service', new MyServiceClass()) app.use('my-service-object', myServiceObject) ``` -------------------------------- ### Example channels.js Configuration Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/channels.md Illustrates setting up real-time channels, handling new connections, user logins, and publishing events. This file is crucial for managing real-time data flow in Feathers applications. ```typescript import type { RealTimeConnection, Params } from '@feathersjs/feathers' import type { Application, HookContext } from './declarations' export default function (app: any) { if (typeof app.channel !== 'function') { // If no real-time functionality has been configured just return return } app.on('connection', (connection: RealTimeConnection) => { // On a new real-time connection, add it to the anonymous channel app.channel('anonymous').join(connection) }) app.on('login', (AuthenticationResult: any, { connection }: Params) => { // connection can be undefined if there is no // real-time connection, e.g. when logging in via REST if (connection) { // The connection is no longer anonymous, remove it app.channel('anonymous').leave(connection) // Add it to the authenticated user channel app.channel('authenticated').join(connection) } }) // eslint-disable-next-line no-unused-vars app.publish((data: any, context: HookContext) => { // Here you can add event publishers to channels set up in `channels.js` // To publish only for a specific event use `app.publish(eventname, () => {})` console.log( 'Publishing all events to all authenticated users. See `channels.js` and https://docs.feathersjs.com/api/channels.html for more information.' ) // e.g. to publish all service events to all authenticated users use return app.channel('authenticated') }) } ``` -------------------------------- ### Setup HTTPS Server Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/koa.md Explicitly call app.setup(server) when creating a separate HTTPS server. This is necessary to initialize all services and SocketIO for HTTPS connections. ```typescript import https from 'https' import { app } from './app' const port = app.get('port') const server = https .createServer( { key: fs.readFileSync('privatekey.pem'), cert: fs.readFileSync('certificate.pem') }, app.callback() ) .listen(443) // Call app.setup to initialize all services and SocketIO app.setup(server) server.on('listening', () => logger.info('Feathers application started')) ``` -------------------------------- ### Install @feathersjs/generators Source: https://github.com/feathersjs/feathers/blob/dove/packages/generators/README.md Install the @feathersjs/generators package as a development dependency. ```bash npm install @feathersjs/generators --save-dev ``` -------------------------------- ### Install @feathersjs/express Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/express.md Install the @feathersjs/express package using npm. ```bash npm install @feathersjs/express --save ``` -------------------------------- ### Initializing the REST Client Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/rest.md Demonstrates how to initialize the Feathers REST client with a base URL and configure it with a chosen AJAX library like Fetch. ```APIDOC ## Initializing the REST Client ### Description Initializes the Feathers REST client with a base URL and configures it to use a specific AJAX library for making HTTP requests. ### Method `rest([baseUrl])` ### Endpoint N/A (Client-side initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { feathers } from '@feathersjs/feathers' import rest from '@feathersjs/rest-client' const app = feathers() // Connect to the same as the browser URL (only in the browser) const restClient = rest() // Connect to a different URL const restClient = rest('http://feathers-api.com') // Configure an AJAX library (e.g., Fetch) app.configure(restClient.fetch(window.fetch.bind(window))) // Access a service const messages = app.service('messages') ``` ### Response N/A (Client-side initialization) ### Error Handling Refer to the documentation of the underlying AJAX library (e.g., Fetch, Axios) for specific error handling. ``` -------------------------------- ### .configure(callback) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Runs a callback function that gets passed the application object. It is used to initialize plugins and can be used to separate your application into different files. This method returns the application instance for chaining. ```APIDOC ## .configure(callback) `app.configure(callback) -> app` runs a `callback` function that gets passed the application object. It is used to initialize plugins and can be used to separate your application into different files. ```ts const setupService = (app: Application) => { app.use('/todos', todoService) } app.configure(setupService) ``` ``` -------------------------------- ### Run Coverage Command on Windows Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/testing.md Example of how to run the coverage command on Windows, setting environment variables and executing nyc with mocha. ```sh npm run clean & SET NODE_ENV=test& nyc mocha ``` -------------------------------- ### Install @feathersjs/errors Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/errors.md Install the @feathersjs/errors module using npm. ```bash npm install @feathersjs/errors --save ``` -------------------------------- ### Load and Configure Feathers Client from CDN Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client.md This example demonstrates how to load the @feathersjs/client and socket.io-client from a CDN using script tags. It then shows how to initialize the Feathers client, configure it with Socket.io, and make a service call. ```html ``` -------------------------------- ### Initialize npm Project (JavaScript) Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/starting.md Initialize a new Node.js project with a package.json file for a JavaScript project. ```sh npm init --yes ``` -------------------------------- ### Example Authentication Configuration Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/authentication/service.md A sample configuration for the authentication service in `config/default.json`. This includes JWT options like secret, issuer, and algorithm. ```json { "authentication": { "secret": "CHANGE_ME", "entity": "user", "service": "users", "authStrategies": ["jwt", "local"], "jwtOptions": { "header": { "typ": "access" }, "audience": "https://yourdomain.com", "issuer": "feathers", "algorithm": "HS256", "expiresIn": "1d" } } } ``` -------------------------------- ### Implementing a Basic Create Method Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/services.md Illustrates how to implement a `create` method in a Feathers service to add a new resource. This example pushes the new data to an internal array and returns the data. ```typescript import type { Id, Params } from '@feathersjs/feathers' type Message = { text: string } class MessageService { messages: Message[] = [] async create(data: Message, params: Params) { this.messages.push(data) return data } } app.use('messages', new MessageService()) ``` -------------------------------- ### Install @feathersjs/koa Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/koa.md Install the Koa integration package for FeathersJS using npm. ```bash npm install @feathersjs/koa --save ``` -------------------------------- ### Initiate GitHub Login Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/basics/login.md Visit this URL to start the GitHub login process. It will redirect to GitHub for authorization. ```text http://localhost:3030/oauth/github ``` -------------------------------- ### View Feathers CLI Help Source: https://github.com/feathersjs/feathers/blob/dove/packages/cli/README.md Display the help information for the Feathers CLI using npx. ```bash npx feathers help ``` -------------------------------- ### Install @feathersjs/schema Source: https://github.com/feathersjs/feathers/blob/dove/packages/schema/README.md Install the @feathersjs/schema package using npm. This command adds the package as a dependency to your project. ```bash npm install @feathersjs/schema --save ``` -------------------------------- ### Install @feathersjs/client Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client.md Install the @feathersjs/client module using npm. This is the command to add the package as a dependency to your project. ```bash npm install @feathersjs/client --save ``` -------------------------------- ### Get Single Resource Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/rest.md Retrieve a single resource by its ID using a GET request to the resource's path. ```http GET /messages/1 ``` -------------------------------- ### app.use(path, service [, options]) Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/application.md Registers a service object on a given path. The path can include URL-friendly strings and placeholders. Options include specifying available methods and events. ```APIDOC ## .use(path, service [, options]) ### Description `app.use(path, service [, options]) -> app` allows registering a [service object](./services.md) on a given `path`. ### Method `app.use` ### Parameters #### Path Parameters - **path** (string) - Required - The URL-friendly string path to register the service on. Can include `/` separators and placeholders like `:userId/messages`. - **service** (object) - Required - The service object to register. - **options** (object) - Optional - Configuration options for the service. - **methods** (string[]) - Optional - A list of official and custom service methods that should be available to clients. Defaults to `['find', 'get', 'create', 'patch', 'update','remove']`. - **events** (string[]) - Optional - A list of public custom events sent by this service. ### Example ```ts import { feathers, type Id } from '@feathersjs/feathers' class MessageService { async get(id: Id) { return { id, text: `This is the ${id} message!` } } } type ServiceTypes = { messages: MessageService } const app = feathers() // Register a service instance on the app app.use('messages', new MessageService()) // Register a service with options app.use('messages', new MessageService(), { methods: ['get', 'doSomething'], events: ['something'] }) ``` ``` -------------------------------- ### Install Feathers Commons Source: https://github.com/feathersjs/feathers/blob/dove/packages/commons/README.md Install the @feathersjs/commons package using npm. This package provides shared utility functions for Feathers applications. ```bash npm install @feathersjs/commons --save ``` -------------------------------- ### Generate Feathers Connection Source: https://github.com/feathersjs/feathers/blob/dove/docs/guides/cli/index.md Sets up a new database connection. This is typically done during application creation but can be used to add additional databases. ```bash npx feathers generate connection ``` -------------------------------- ### Feathers REST Client Initialization and Service Configuration Source: https://github.com/feathersjs/feathers/blob/dove/docs/api/client/rest.md Shows how to initialize the Feathers REST client and configure a service with route placeholders. This example connects to a specific API endpoint. ```typescript import { feathers } from '@feathersjs/feathers' import rest from '@feathersjs/rest-client' const app = feathers() // Connect to the same as the browser URL (only in the browser) const restClient = rest() // Connect to a different URL const restClient = rest('http://feathers-api.com') // Configure an AJAX library (see below) with that client app.configure(restClient.fetch(window.fetch.bind(window))) // Connect to the `http://feathers-api.com/messages` service const messages = app.service('users/:userId/messages') ```