简体   繁体   中英

meteor 1.10.2 typescript ValidatedMethod - this.userId

I'm struggling with meteor typescript and mdg:ValidatedMethod .

I used the @types from This Repo for mdg:ValidatedMethod .

Let's assume this meteor code without the ValidateMethod:

const addLink = Meteor.methods({
  'links.add'({ title,url }) {
    new SimpleSchema({
      title: { type: String },
      url: {type: String}
    }).validate({ title,url });


    if (!this.userId) {
      //throw an error!
    }

    LinksCollection.insert({
      title,
      url,
      createdAt: new Date(),
    });
  }
});

Here all works as supposed, no error on if (this.userId) {

However, when i now change to the ValidatedMethod, typescript can't find this.userId

const addLink = new ValidatedMethod({
  name: 'links.add',
  validate: new SimpleSchema({
      title: { type: String },
      url: {type: String}
    }).validator(),
    run({title,url}) {
      if (!this.userId) { //Here typescript can't find this.userId
        //throw an error!
      }
  
      LinksCollection.insert({
        title,
        url,
        createdAt: new Date(),
      });
    }
});

I checked the type from the first example and added the this -ref the run method in the @type-definition, which means i changed line 17 from

run: (args: { [key: string]: any; }) => void;

to

run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;

I seems to work now, however as I'm pretty new to the typescript world, i was wondering, if this is the right way to do?!

TypeScript lets you define the type of this like so:

function f(this: ThisType) {}

See here for more info: https://www.typescriptlang.org/docs/handbook/functions.html

In this specific case you could add

this: Meteor.MethodThisType

to the run method signature in the index.d.ts:

run: (this: Meteor.MethodThisType, args: { [key: string]: any; }) => void;

It's not totally complete as ValidatedMethod defines a couple extra parameters (eg. this.name ) but you can add those if you need them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM