Last active
November 17, 2018 02:51
-
-
Save daffl/cbbd310ab6fb4b5ed0968f1527d0a966 to your computer and use it in GitHub Desktop.
Example service middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MessageService { | |
// Find a list of resources | |
find(params) {}, | |
// Get a single resource by its id | |
get(id, params) {}, | |
// Create a new resource | |
create(data, params) {}, | |
// Replace an existing resource by its id with data | |
update(id, data, params) {}, | |
// Merge new data into a resource | |
patch(id, data, params) {}, | |
// Remove a resource by its id | |
remove(id, params) {} | |
} | |
const messages = new MessageService(); | |
// Log the runtime for all method calls | |
messages.use(async (ctx, next) => { | |
// Store the start time | |
const start = Date.now(); | |
// Pass to the next middleware and wait for everything to return | |
await next(); | |
// Calculate the total runtime everything took | |
const ms = Date.now() - start; | |
// Log runtime with method name | |
console.log(`Calling ${ctx.method} took ${ms}ms`); | |
}); | |
messages.use({ | |
// For `create`, add the current date as `createdAt` before saving everything to the database | |
create: [async (ctx, next) => { | |
ctx.data.createdAt = new Date(); | |
// Go on to the next step (actual service `create` in this case) | |
await next(); | |
}] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment