jam:method

v1.8.0Published 2 months ago

Method

Method is an easy way to create Meteor methods with Optimistic UI. It's built with Meteor 3.0 in mind and is compatible with Meteor 2.x to make migration easy. It's meant to be a drop in replacement for Validated Method and comes with additional features:

  • Before and after hooks
  • Global before and after hooks for all methods
  • Pipe a series of functions
  • Authed by default (can be overriden)
  • Easily configure a rate limit
  • Optionally run a method on the server only
  • Attach the methods to Collections (optional)
  • Validate with one of the supported schema packages or a custom validate function
  • No need to use .call to invoke the method as with Validated Method

Usage

Add the package to your app

meteor add jam:method

Create a method

name is required and will be how Meteor's internals identifies it.

schema will automatically validate using a supported schema.

run will be executed when the method is called.

1import { createMethod } from 'meteor/jam:method'; // can import { Methods } from 'meteor/jam:method' instead and use Methods.create if you prefer
2
3export const create = createMethod({
4  name: 'todos.create',
5  schema: Todos.schema, // using jam:easy-schema in this example
6  async run({ text }) {
7    const todo = {
8      text,
9      done: false,
10      createdAt: new Date(),
11      authorId: Meteor.userId(), // can also use this.userId instead of Meteor.userId()
12    }
13    const todoId = await Todos.insertAsync(todo);
14    return todoId;
15  }
16});

Supported schemas

Currently, these schemas are supported:

If you're using jam:easy-schema, be sure to check out Using with jam:easy-schema below for details on a way to write methods with less boilerplate.

Here's a quick example of each one's syntax. They vary in features so pick the one that best fits your needs.

1// jam:easy-schema. you'll attach to a Collection so you can reference one {Collection}.schema in your methods
2const schema = {text: String, isPrivate: Optional(Boolean)}
3// check
4const schema = {text: String, isPrivate: Match.Maybe(Boolean)}
5// zod
6const schema = z.object({text: z.string(), isPrivate: z.boolean().optional()})
7// simpl-schema
8const schema = new SimpleSchema({text: String, isPrivate: {type: Boolean, optional: true}})

Custom validate function

If you're not using one of the supported schemas, you can use validate to pass in a custom validation function. Note: validate can be an async function if needed.

1// import your schema from somewhere
2// import your validator function from somewhere
3
4export const create = createMethod({
5  name: 'todos.create',
6  validate(args) {
7    validator(args, schema)
8  },
9  async run({ text }) {
10    const todo = {
11      text,
12      done: false,
13      createdAt: new Date(),
14      authorId: Meteor.userId() // can also use this.userId instead of Meteor.userId()
15    }
16    const todoId = await Todos.insertAsync(todo);
17    return todoId;
18  }
19});

Import on the client and use

1import { create } from '/imports/api/todos/methods';
2
3async function submit() {
4  try {
5    await create({text: 'book flight to Hawaii'})
6  } catch(error) {
7    alert(error)
8  }
9}

Before and after hooks

You can execute functions before and / or after the method's run function. before and after accept a single function or an array of functions.

When using before, the original input passed into the method will be available. The original input will be returned automatically from a before function so that run receives what was originally passed into the method.

A great use case for using before is to verify the user has permission. For example:

1async function checkOwnership({ _id }) { // the original input passed into the method is available here. destructuring for _id since that's all we need for this function
2  const todo = await Todos.findOneAsync(_id);
3  if (todo.authorId !== Meteor.userId()) {
4    throw new Meteor.Error('not-authorized')
5  }
6
7  return true; // any code executed as a before function will automatically return the original input passed into the method so that they are available in the run function
8}
9
10export const markDone = createMethod({
11  name: 'todos.markDone',
12  schema: Todos.schema,
13  before: checkOwnership,
14  async run({ _id, done }) {
15    return await Todos.updateAsync(_id, {$set: {done}});
16  }
17});

When using after, the result of the run function will be available as the first argument and the second argument will contain the original input that was passed into the method. The result of the run function will be automatically returned from an after function.

1function exampleAfter(result, context) {
2  const { originalInput } = context; // the name of the method is also available here
3  // do stuff
4
5  return 'success'; // any code executed as an after function will automatically return the result of the run function
6}
7
8export const markDone = createMethod({
9  name: 'todos.markDone',
10  schema: Todos.schema,
11  before: checkOwnership,
12  async run({ _id, done }) {
13    return await Todos.updateAsync(_id, {$set: {done}});
14  },
15  after: exampleAfter
16});

Note: If you use arrow functions for before, run, or after, you'll lose access to this – the methodInvocation. You may be willing to sacrifice that because this.userId can be replaced by Meteor.userId() and this.isSimulation can be replaced by Meteor.isClient but it's worth noting.

Pipe a series of functions

Instead of using run, you can compose functions using .pipe. Each function's output will be available as an input for the next function.

1// you'd define the functions in the pipe and then place them in the order you'd like them to execute within .pipe
2// be sure that each function in the pipe returns what the next one expects, otherwise you can add an arrow function to the pipe to massage the data, e.g. (input) => manipulate(input)
3
4export const create = createMethod({
5  name: 'todos.create',
6  schema: Todos.schema
7}).pipe(
8  checkOwnership,
9  createTodo,
10  sendNotification
11)

Attach methods to its Collection (optional)

Instead of importing each method, you can attach them to the Collection. If you're using jam:easy-schema be sure to attach the schema before attaching the methods.

1// /imports/api/todos/collection
2import { Mongo } from 'meteor/mongo';
3import { schema } from './schema';
4
5export const Todos = new Mongo.Collection('todos');
6
7Todos.attachSchema(schema); // if you're using jam:easy-schema
8
9const attach = async () => {
10  const methods = await import('./methods.js') // dynamic import is recommended
11  return Todos.attachMethods(methods); // if you prefer not to use dynamic import, you can simply call attachMethods synchronously
12};
13
14attach().catch(error => console.error('Error attaching methods', error))

attachMethods accepts the method options as an optional second parameter. See Configuring for a list of the options.

With the methods attached you'll use them like this on the client:

1import { Todos } from '/imports/api/todos/collection';
2// no need to import each method individually
3
4async function submit() {
5  try {
6    await Todos.create({text: 'book flight to Hawaii'})
7  } catch(error) {
8    alert(error)
9  }
10}

Executing code on the server only

By default, methods are optimistic meaning they will execute on the client and then on the server. If there's only part of the method that should execute on the server and not on the client, then simply wrap that piece of code in a if (Meteor.isServer) block. This way you can still maintain the benefits of Optimistic UI. For example:

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  async run(args) {
5    // rest of your function
6    // code running on both client and server
7    if (Meteor.isServer) {
8      // code running on the server only
9      import { secretCode } from '/server/secretCode'; // since it's in a /server folder the code will not be shipped to the client
10      // do something with secretCode
11    }
12
13    // code running on both client and server
14    return Todos.insertAsync(todo)
15  }
16});

If you prefer, you can force the entire method to execute on the server only by setting serverOnly: true. It can be used with run or .pipe. Here's an example with run:

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  serverOnly: true,
5  async run(args) {
6    // all code here will execute only on the server
7  }
8});

You can also set all methods to be serverOnly. See Configuring below.

Security note

Important: Since Meteor does not currently support tree shaking, the contents of the code inside run function or .pipe could still be visible to the client even if you use if (Meteor.isServer) or serverOnly: true. To prevent this, you have these options:

  1. Attach methods to its Collection with a dynamic import as shown above Attach methods to its Collection (optional)

  2. Import function(s) from a file within a /server folder. Any code imported from a /server folder will not be shipped to the client. The /server folder can be located anywhere within your project's file structure and you can have multiple /server folders. For example, you can co-locate with your collection folder, e.g. /imports/api/todos/server/, or it can be at the root of your project. See Secret server code for more info.

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  serverOnly: true,
5  async run(args) {
6    import { serverFunction } from '/server/serverFunction';
7
8    serverFunction(args);
9  }
10});
  1. Dynamically import function(s). These do not have to be inside a /server folder. This will prevent the code being inspectable via the browser console.
1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  serverOnly: true,
5  async run(args) {
6    const { serviceFunction } = await import('./services');
7
8    serviceFunction(args);
9  }
10});

Changing authentication rules

By default, all methods will be protected by authentication, meaning they will throw an error if there is not a logged-in user. You can change this for an individual method by setting open: true. See Configuring below to change it for all methods.

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  open: true,
5  async run({ text }) {
6    // ... //
7  }
8});

Rate limiting

Easily rate limit a method by setting its max number of requests – the limit – within a given time period (milliseconds) – the interval.

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  rateLimit: { // rate limit to a max of 5 requests every second
5    limit: 5,
6    interval: 1000
7  },
8  async run({ text }) {
9    // ... //
10  }
11});

Validate without executing the method

There may be occassions where you want to validate without executing the method. In these cases, you can use .validate. If you want to validate against only part of the schema, use .validate.only.

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  async run({ text }) {
5    // ... //
6  }
7});
8
9// validate against the schema without executing the method
10create.validate({...})
11
12// validate against only the relevant part of the schema based on the data passed in without executing the method
13create.validate.only({...})

If you're using a custom validate function instead of one of the supported schemas and you'd like to use .validate.only, you can simply append an only function onto the validate function that you supply.

Options for Meteor.applyAsync

When called, the method uses Meteor.applyAsync under the hood to execute your run function or .pipe function(s). Meteor.applyAsync takes a few options which can be used to alter the way Meteor handles the method. If you want to change the defaults or include other supported options, pass in options when creating the method.

1export const create = createMethod({
2  name: 'todos.create',
3  schema: Todos.schema,
4  options: {
5    // ... //
6  },
7  async run({ text }) {
8    // ... //
9  }
10});

By default, this package uses the following options:

1{
2  // Make it possible to get the ID of an inserted item
3  returnStubValue: true,
4
5  // Don't call the server method if the client stub throws an error, so that we don't end
6  // up doing validations twice
7  throwStubExceptions: true,
8};

See Configuring below to set options for all methods.

Working with the stub result (Meteor 3.0+)

In Meteor 3.0+, you can optionally take action with the stub result, i.e. the result when the method simulation is run on the client, before the server has returned with the final result or error. This can come in handy when you want to make your app feel instant for the user and you're relatively sure the action will succeed, e.g. when inserting new documents into the database.

1  const { stubPromise, serverPromise } = create();
2  const _id = await stubPromise.catch(error => {
3    // optionally handle a stub error
4  });
5
6  // take action with the _id stub result, for example, route to a new page
7  router.go(`/detail/${_id}`)
8
9  await serverPromise.catch(error => {
10    // handle server error, rollback changes as needed, for example route to home
11    router.go('/')
12    alert('sorry, could not create')
13  });

Mocking the method context

You can mock the method invocation context, aka the this value inside the method, by invoking the method with .call(context, args). This is particularly useful for unit testing to mock the this.userId:

1const context = {
2  userId: 'fakeUserId',
3  // ... //
4}
5
6await create.call(context, {...})

Configuring (optional)

If you like the defaults, then you won't need to configure anything. But there is some flexibility in how you use this package.

Here are the global defaults:

1const config = {
2  before: [], // global before function(s) that will run before all methods
3  after: [], // global after function(s) that will run after all methods
4  serverOnly: false, // globally make all methods serverOnly, aka disable Optimistic UI, by setting to true
5  options: {
6    returnStubValue: true, // make it possible to get the ID of an inserted item on the client before the server finishes
7    throwStubExceptions: true,  // don't call the server method if the client stub throws an error, so that we don't end up doing validations twice
8  },
9  open: false, // by default all methods will be protected by authentication, override it for all methods by setting this to true
10  loggedOutError: new Meteor.Error('logged-out', 'You must be logged in') // customize the logged out error
11};

To change the global defaults, use:

1// put this in a file that's imported on both the client and server
2import { Methods } from 'meteor/jam:method';
3
4Methods.configure({
5  // ... change the defaults here ... //
6});

Global before and after hooks

You can create before and/or after functions to run before / after all methods. Both before and after accept a single function or an array of functions.

1import { Methods } from 'meteor/jam:method';
2
3const hello = () => { console.log('hello') }
4const there = () => { console.log('there') }
5const world = () => { console.log('world') }
6
7Methods.configure({
8  before: [hello, there],
9  after: world
10});

Helpful utility function to log your methods

Here's a helpful utility function - log - that you might consider adding. It isn't included in this package but you can copy and paste it into your codebase where you see fit.

1// log will simply console.log or console.error when the Method finishes
2function log(input, pipeline) {
3  pipeline.onResult((result) => {
4    console.log(`Method ${pipeline.name} finished`, input);
5    console.log('Result', result);
6  });
7
8  pipeline.onError((err) => {
9    console.error(`Method ${pipeline.name} failed`);
10    console.error('Error', err);
11  });
12};

Then you could use it like this:

1import { Methods, server } from 'meteor/jam:method';
2
3Methods.configure({
4  after: server(log)
5});

Alternative functional-style syntax

You can use a functional-style syntax to compose your methods if you prefer. Here's an example.

1const fetchGifs = async({ searchTerm, limit }) => {...}
2
3export const getGifs = createMethod(server(schema({ searchTerm: String, limit: Number })(fetchGifs)))

getGifs is callable from the client but will only run on the server. Internally it will be identified as fetchGifs

Note: if you pass in a named function into createMethod, then that will be used to identify the method internally. Otherwise if you pass in an anonymous function, jam:method generates a unique name based on its schema to identify it internally.

Customizing methods when using functional-style syntax

There are a few functions available when you need to customize the method: schema, server, open, close. These can be composed when needed.

schema

Specify the schema to validate against.

1import { schema } from 'meteor/jam:method';
2
3export const doSomething = schema({thing: String, num: Number})(async ({ thing, num }) => {
4  // ... //
5});

server

Make the method run on the server only.

1import { server } from 'meteor/jam:method';
2
3export const aServerOnlyMethod = server(async data => {
4  // ... //
5});

open

Make the method publically available so that a logged-in user isn't required.

1import { open } from 'meteor/jam:method';
2
3export const aPublicMethod = open(async data => {
4  // ... //
5});

close

Make the method check for a logged-in user.

Note: by default, all methods require a logged-in user so if you stick with that default, then you won't need to use this function. See Configuring.

1import { close } from 'meteor/jam:method';
2
3export const closedMethod = close(async data => {
4  // ... //
5});

Using with jam:easy-schema

jam:method integrates with jam:easy-schema and offers a way to reduce boilerplate and make your methods even easier to write (though you can still use createMethod if you prefer).

For example, instead of writing this:

1export const setDone = createMethod({
2  name: 'todos.setDone',
3  schema: Todos.schema,
4  before: checkOwnership,
5  async run({ _id, done }) {
6    return Todos.updateAsync({ _id }, { $set: { done } });
7  }
8});

You can write:

1export const setDone = async ({ _id, done }) => {
2  await checkOwnership({ _id });
3  return Todos.updateAsync({ _id }, { $set: { done } });
4};

Note: This assumes that you're attaching your methods to its collection. See Attach methods to its Collection.

When you call Todos.setDone from the client, the arguments will be automatically checked against the Todos.schema. The method will automatically be named todos.setDone internally to identify it for app performance monitoring (APM) purposes.

You can also compose with the functions available in the function-style syntax. For example:

1export const setDone = server(async ({ _id, done }) => {
2  await checkOwnership({ _id });
3  return Todos.updateAsync({ _id }, { $set: { done } });
4});

Now when you call Todos.setDone from the client it will only run on the server.

Using with jam:offline

jam:method integrates with jam:offline to automatically queue methods when a user is offline. You don't need to configure anything in jam:method for this. 🎉 jam:offline will then replay them when the user reconnects. See jam:offline for more details.

Coming from Validated Method?

You may be familiar with mixins and wondering where they are. With the features of this package - authenticated by default, before / after hooks, .pipe - your mixin code may no longer be needed or can be simplified. If you have another use case where your mixin doesn't translate, I'd love to hear it. Open a new discussion and let's chat.