RouteHandler "this" type missing [Typescript]
I'm using the library with Typescript and am unsure how to handle the this type in my route handlers. I know I could explicitly type it for every route handler but I can't find any exported type to plug in. Also it's kind of a drag having to do this all over.
Here's an example of route handler with this set to any:
this.post(
'some/endpoint',
function (this: any, schema, req) {
const { query } = JSON.parse(req.requestBody);
const results = schema.where('something', { id: query });
const { stuff } = this.serialize(results);
return doSomethingWithSerializedData(stuff);
}
);
Removing this: any will yield a compiler error when trying to use this.serialize(results).
Everything else works just fine. Love this library! ❤️
I have no idea if I've done it correctly, but my approach seems to be working for me so far (caveat: I don't have fancy models or factories, but they are typed correctly).
export const serverConfig: ServerConfig<typeof models, typeof factories> = {
models,
factories,
...
routes() {
// "this" will be typed correctly
},
};
And if you need the type of this elsewhere, you can use
import type { Registry } from 'miragejs';
// eslint-disable-next-line import/no-unresolved
import type { Server } from 'miragejs/server';
type MockServer = Server<Registry<typeof models, typeof factories>>;
Maybe others can chime in with something more elegant, but like I said, that's been working for me.
Edit: I just noticed that you're trying to treat the first argument to the callback as this. That's not the arguments I use, I only use (schema, request). I'll do a little digging to see if I can figure out what's going on.
I see https://miragejs.com/docs/main-concepts/serializers/#working-with-serialized-json. It's possible that the serialize method is just missing from the typescript definitions. Just an idea, but could you call your serializer directly, rather than pulling the method off the route handler?
Hey, thanks for the reply. The types of my models and factories are inferred correctly, so I can use e.g. schema and have proper autocomplete. I added the this argument to the route handler callback since it's not inferred properly. It's kind of a pseudo-argument --> Typescript docs.
Haven't found a way to use the serializer directly either. 😞
I have to do this as well and it's also bothering my pedantic side a little bit:
// eslint-disable-next-line import/no-unresolved
import type { Server } from 'miragejs/server';