Skip to content

Instantly share code, notes, and snippets.

@daffl
Last active November 17, 2018 02:51
Show Gist options
  • Save daffl/cbbd310ab6fb4b5ed0968f1527d0a966 to your computer and use it in GitHub Desktop.
Save daffl/cbbd310ab6fb4b5ed0968f1527d0a966 to your computer and use it in GitHub Desktop.
Example service middleware
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