TS ERROR: Type 'AxiosResponse<IChat, any>' is not assignable to type 'IChat' - node.js

I have class with method:
export default class ChatService {
static async findDMChat(companionID: number) {
return $api.post<IChat>('/findDMChat', {companion_id: companionID})
}
}
In ChatStore.setCompanion( ) I want to assign result of that method to property:
export class ChatStore {
companion = {} as IUser;
chat = {} as IChat;
constructor() {
makeAutoObservable(this)
}
async setCompanion(companion: IUser) {
this.companion = companion;
this.chat = await ChatService.findDMChat(companion.id) // Type 'AxiosResponse<IChat, any>' is missing the following properties from type 'IChat': type, idts(2739)
}
Description of the error is indicated in the code comment.
Thanks in advance.

await ChatService.findDMChat(companion.id) return the result of response, not just data. If you look at AxiosResponse type you'll see what response includes
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
request?: any;
}
so, in your case you should get data property from response
const { data} = await ChatService.findDMChat(companion.id);
this.chat = data;

Related

Nestjs - Use applyDecorators inside createParamDecorator

I'm using Nestjs decorators and am trying to make the most of custom decorators. I'm trying to write my own custom #Body param decorator that validates and applies multiple decorators at the same time.
Does anyone know if the below is possible? I'm having difficulty getting the second argument in the transform call of the pipes to have metadata: ArgumentMetadata.
export const MyParamDecorator = <T>(myDto: T) => {
return createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
applyDecorators( // also get SetMeta and Pipes to validate DTO
SetMetadata('thisWorks', true)
UsePipes(CustomValidationPipe, OtherPipe), // + add MyDTO - type T somehow..
);
return doAsyncWork()
},
)();
}
#Controller('users')
export class UsersController {
#Patch(':id')
update(#MyParamDecorator() asyncWork: Promise<any>) { // <------ Promise<any> is custom async opperation that will be handled. (So I can't type the DTO here..)
return reqBody;
}
}
I ran across this question because I needed a similar answer. Hopefully what I've found is helpful.
Part 1. You can do async processing in a decorator.
And, it would resolve for you, so your controller would look like:
update(#MyParamDecorator() asyncWork: any) {
Notice that Promise<any> is just any.
Part 2. You can get ArgumentMetadata using an enhancer.
Here is a quick example, let's assume METADATA__PARAM_TYPE is myType.
param-type.enhancer.ts
export const paramTypeEnhancer: ParamDecoratorEnhancer = (
target: Record<string, unknown>,
propertyKey: string,
parameterIndex: number,
): void => {
const paramTypes = Reflect.getOwnMetadata('design:paramtypes', target, propertyKey);
const metatype = paramTypes[parameterIndex];
Reflect.defineMetadata(METADATA__PARAM_TYPE, metatype, target[propertyKey]);
};
my-decorator.ts
import { paramTypeEnhancer } from './param-type.enhancer';
export const MyDecorator = createParamDecorator(
async (data: unknown, ctx: ExecutionContext): Promise<any> => {
const metatype = Reflect.getOwnMetadata(METADATA__PARAM_TYPE, ctx.getHandler());
const argument: ArgumentMetadata = {
type: 'custom',
data: undefined,
metatype: metatype,
};
// Do processing here... You can return a promise.
},
[paramTypeEnhancer],
);
See this gist for a full annotated version: https://gist.github.com/josephdpurcell/fc04cfd428a6ee9d7ffb64685e4fe3a6

How to pass a child Interface to a parent class?

I have this:
LocationController.ts
import {GenericController} from './_genericController';
interface Response {
id : number,
code: string,
name: string,
type: string,
long: number,
lat: number
}
const fields = ['code','name','type','long','lat'];
class LocationController extends GenericController{
tableName:string = 'location';
fields:Array<any> = fields;
}
const locationController = new LocationController();
const get = async (req, res) => {
await locationController._get(req, res);
}
export {get};
GenericController.ts
interface Response {
id : number
}
export class GenericController{
tableName:string = '';
fields:Array<any> = [];
_get = async (req, res) => {
try{
const id = req.body['id'];
const send = async () => {
const resp : Array<Response> = await db(this.tableName).select(this.fields).where('id', id)
if (resp[0] === undefined) {
// some error handling
}
res.status(status.success).json(resp[0]);
}
await send();
}catch (error){
// some error handling
}
}
}
What I want to do is to pass the Response interface from LocationController to the GenericController parent, so that the response is typed accurately depending on how the child class has defined it. Clearly it doesn't work like this since the interface is defined outside of the class so the parent has no idea about the Response interface in the LocationController.ts file.
I've tried passing interface as an argument in the constructor, that doesn't work. So is there a way I can make this happen? I feel like I'm missing something really simple.
Typically, generics are used in a situation like this. Here's how I'd do it:
interface Response {
id: number;
}
// Note the generic parameter <R extends Response>
export class GenericController<R extends Response> {
tableName: string = "";
fields: Array<any> = [];
_get = async (req, res) => {
try {
const id = req.body["id"];
const send = async () => {
// The array is now properly typed. You don't know the exact type,
// but you do know the constraint - R is some type of `Response`
let resp: Array<R> = await db(this.tableName).select(this.fields).where("id", id);
if (resp[0] === undefined) {
// some error handling
}
res.status(status.success).json(resp[0]);
};
await send();
} catch (error) {
// some error handling
}
};
}
import { GenericController } from "./_genericController";
interface Response {
id: number;
code: string;
name: string;
type: string;
long: number;
lat: number;
}
const fields = ["code", "name", "type", "long", "lat"];
// Here we tell the GenericController exactly what type of Response it's going to get
class LocationController extends GenericController<Response> {
tableName: string = "location";
fields: Array<any> = fields;
}
const locationController = new LocationController();
const get = async (req, res) => {
await locationController._get(req, res);
};
export { get };
If this is not enough and you wish to somehow know the exact response type you're going to get, I believe the only way is a manual check. For example:
import { LocationResponse } from './locationController';
// ... stuff
// Manual runtime type check
if (this.tableName === 'location') {
// Manual cast
resp = resp as Array<LocationResponse>
}
// ...
You could also check the form of resp[0] (if (resp[0].hasOwnProperty('code')) { ... }) and cast accordingly. There are also nicer ways to write this, but the basic idea remains the same.
Generally, a properly written class should be unaware of any classes that inherit from it. Putting child-class-specific logic into your generic controller is a code smell. Though as always, it all depends on a particular situation.

Argument of type 'typeof globalThis' is not assignable to parameter of type 'EntryService'

I'm trying to pass my service to an instance of a class that I pass to a method decorator.
Here's the service:
#Injectable()
export class EntryService {
constructor(
#InjectRepository(EntryEntity)
private readonly entryRepository: Repository<EntryEntity>,
#InjectRepository(ImageEntity)
private readonly imageRepository: Repository<ImageEntity>,
private readonly awsService: AwsService,
private readonly connection: Connection,
private readonly categoriesService: CategoriesService,
private readonly cacheService: CacheService,
private readonly usersService: UserService,
private readonly imagesService: ImagesService,
private readonly notificationService: NotificationsService,
) {}
#RecordEntryOperation(new CreateOperation(this))
public async create(createEntryDto: CreateEntryBodyDto): Promise<Entry> {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.commitTransaction();
// more code
} catch (err) {
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
}
}
The thing here is that I need to use EntryService inside that class I pass to the RecordEntryOperation decorator.
The decorator (not fully implemented yet):
export const RecordEntryOperation = (operation: Operation) => {
return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => {
const original = descriptor.value;
descriptor.value = async function(...args: any[]) {
const response = await original.apply(this, args);
console.log(`operation.execute()`, await operation.execute());
return response;
};
};
};
The CreateOperation class looks like this (not fully implemented yet):
export class CreateOperation extends Operation {
constructor(public entryService: EntryService) { super(); }
public async execute(): Promise<any> {
return this.entryService.someEntryServiceOperation();
}
}
The error I'm getting reads as follows:
Argument of type 'typeof globalThis' is not assignable to parameter of type 'EntryService'.
Type 'typeof globalThis' is missing the following properties from type 'EntryService': entryRepository, imageRepository, awsService, and 53 more.
I don't fully understand what this error is about. I suspect that it means that the this passed to the CreateOperation class does not have all these dependencies injected into the service by the dependency injector.
I tried different things, but to no avail. Seems like I don't completely understand what is going on.
Any ideas?
What would be the right way to structure the code then?
The problem is the following line:
#RecordEntryOperation(new CreateOperation(this))
this does not refer to the instance of EntryService as you might expect, instead it refers to the globalThis (that this actually refers to the current module), thus the error. What you could do is to change your Operation-class a bit and pass the entryService to the execute method.
export class CreateOperation extends Operation {
constructor() { super(); }
public async execute(entryService: EntryService): Promise<any> {
return entryService.someEntryServiceOperation();
}
}
Then you can do the following in your decorator:
export const RecordEntryOperation = (OperationType: typeof CreateOperation) => {
return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => {
const operation = new OperationType();
const original = descriptor.value;
descriptor.value = async function(...args: any[]) {
const response = await original.apply(this, args);
console.log(`operation.execute()`, await operation.execute(this));
return response;
};
};
};
Then use it with:
#RecordEntryOperation(CreateOperation)
public async create(createEntryDto: CreateEntryBodyDto): Promise<Entry> { .. }

How to Type Fastify Reply payloads?

I'm just getting into Fastify with Typescript and really enjoying it.
However, I'm trying to figure out if I can type the response payload. I have the response schema for serialization working and that may be sufficient, but I have internally typed objects (such as IUser) that it would be nice to have Typescript check against.
The following works great, but I'd like to return an TUser for example and have typescript if I return something different. Using schema merely discludes fields.
interface IUser {
firstname: string,
lastname: string
} // Not in use in example
interface IUserRequest extends RequestGenericInterface {
Params: { username: string };
}
const getUserHandler = async (
req: FastifyRequest<IUserRequest, RawServerBase, IncomingMessage | Http2ServerRequest>
) => {
const { username } = req.params;
return { ... }; // Would like to return instance of IUser
};
app.get<IUserRequest>('/:username', { schema }, helloWorldHandler);
Is there an equivalent of RequestGenericInterface I can extend for the response?
Small Update: It seems that the reply.send() can be used to add the type, but it would be nice for self-documentation sake to provide T higher up.
From the documentation:
Using the two interfaces, define a new API route and pass them as generics. The shorthand route methods (i.e. .get) accept a generic object RouteGenericInterface containing five named properties: Body, Querystring, Params, Headers and Reply.
You can use the Reply type.
interface MiscIPAddressRes {
ipv4: string
}
server.get<{
Reply: MiscIPAddressRes
}>('/misc/ip-address', async (req, res) => {
res
.status(_200_OKAY)
.send({
ipv4: req.ip // this will be typechecked
})
})
After looking at the type definitions, I found out that there is also an alternative way to only type-check the handler (like in Julien TASSIN's answer), like this:
import { FastifyReply, FastifyRequest, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault } from "fastify";
import { RouteGenericInterface } from "fastify/types/route";
interface IUser {
firstname: string;
lastname: string;
}
interface IUserRequest extends RouteGenericInterface {
Params: { username: string };
Reply: IUser; // put the response payload interface here
}
function getUserHandler(
request: FastifyRequest<IUserRequest>,
reply: FastifyReply<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
IUserRequest // put the request interface here
>
) {
const { username } = request.params;
// do something
// the send() parameter is now type-checked
return reply.send({
firstname: "James",
lastname: "Bond",
});
}
You can also create your own interface with generic to save writing repeating lines, like this:
import { FastifyReply, FastifyRequest, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault } from "fastify";
import { RouteGenericInterface } from "fastify/types/route";
export interface FastifyReplyWithPayload<Payload extends RouteGenericInterface>
extends FastifyReply<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
Payload
> {}
then use the interface like this:
function getUserHandler(
request: FastifyRequest<IUserRequest>,
reply: FastifyReplyWithPayload<IUserRequest>
) {
const { username } = request.params;
// do something
// the send() parameter is also type-checked like above
return reply.send({
firstname: "James",
lastname: "Bond",
});
}
If you want to type the handler only, you can perform it this way
import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod } from "fastify";
const getUserHandler: RouteHandlerMethod<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
{ Reply: IUser; Params: { username: string } }
> = async (
req: FastifyRequest<IUserRequest, RawServerBase, IncomingMessage | Http2ServerRequest>
) => {
const { username } = req.params;
return { ... }; // Would like to return instance of IUser
};
Trying to type these was a truely awful experience. Thanks to the other answers, this is where I ended up. Bit of a code dump to make life easier for others.
request-types.ts
With this I am standardising my response to optionally have data and message.
import {
FastifyReply,
FastifyRequest,
RawReplyDefaultExpression,
RawRequestDefaultExpression,
RawServerDefault,
} from 'fastify';
type ById = {
id: string;
};
type ApiRequest<Body = void, Params = void, Reply = void> = {
Body: Body;
Params: Params;
Reply: { data?: Reply & ById; message?: string };
};
type ApiResponse<Body = void, Params = void, Reply = {}> = FastifyReply<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
ApiRequest<Body, Params, Reply>
>;
type RouteHandlerMethod<Body = void, Params = void, Reply = void> = (
request: FastifyRequest<ApiRequest<Body, Params, Reply>>,
response: ApiResponse<Body, Params, Reply>
) => void;
export type DeleteRequestHandler<ReplyPayload = ById> = RouteHandlerMethod<void, ById, ReplyPayload>;
export type GetRequestHandler<ReplyPayload> = RouteHandlerMethod<void, ById, ReplyPayload>;
export type PostRequestHandler<Payload, ReplyPayload> = RouteHandlerMethod<Payload, void, ReplyPayload>;
export type PatchRequestHandler<Payload, ReplyPayload> = RouteHandlerMethod<Payload, ById, ReplyPayload>;
export type PutRequestHandler<Payload, ReplyPayload> = RouteHandlerMethod<Payload, ById, ReplyPayload>;
Usage
get-account.ts - GetRequestHandler
export const getAccount: GetRequestHandler<AccountResponseDto> = async (request, reply) => {
const { id } = request.params;
...
const account = await Account.findOne....
...
if (account) {
return reply.status(200).send({ data: account });
}
return reply.status(404).send({ message: 'Account not found' });
};
delete-entity.ts - DeleteRequestHandler
export const deleteEntity: DeleteRequestHandler = async (request, reply) => {
const { id } = request.params;
...
// Indicate success by 200 and returning the id of the deleted entity
return reply.status(200).send({ data: { id } });
};
update-account.ts - PatchRequestHandler
export const updateAccount: PatchRequestHandler<
UpdateAccountRequestDto,
AccountResponseDto
> = async (request, reply) => {
const { id } = request.params;
...
return reply.status(200).send({ data: account });
};
register-account-routes.ts - No errors with provided handler.
export const registerAccountRoutes = (app: FastifyInstance) => {
app.get(EndPoints.ACCOUNT_BY_ID, getAccount);
app.patch(EndPoints.ACCOUNT_BY_ID, updateAccount);
app.post(EndPoints.ACCOUNTS_AUTHENTICATE, authenticate);
app.put(EndPoints.ACCOUNTS, createAccount);
};

Angular 2 Universal + Akamai

I want to see if I can create a stack based on both, CDN and also angular 2 universal. So when the user navigate has the CDN to get the assets, and if the user access the first time will have the complete html rendered by Universal.
I was thinking in:
Client <===> Akamai <===> Varnish <===> Origin Server (node.js with universal)
This sounds good? have you ever tried it?
Also i'm considering adding nginx and ELB for the complete stack.
The question is:
- Can this stack work as expected?
Yes it can be done! The big issue is how do you invalidate an arbitrary number of http requests made in Angular that determine the rendered page. Using some sort of header schema to invalidate might be helpful.
Assuming your are using official ng-express engine, a service like this could let you define the response from the Angular runtime:
import { RESPONSE } from '#nguniversal/express-engine/tokens'
import { Inject, Injectable, Optional } from '#angular/core'
import { Response } from 'express'
export interface IServerResponseService {
getHeader(key: string): string
setHeader(key: string, value: string): this
setHeaders(dictionary: { [key: string]: string }): this
appendHeader(key: string, value: string, delimiter?: string): this
setStatus(code: number, message?: string): this
setNotFound(message?: string): this
setError(message?: string): this
}
#Injectable()
export class ServerResponseService implements IServerResponseService {
private response: Response
constructor(#Optional() #Inject(RESPONSE) res: any) {
this.response = res
}
getHeader(key: string): string {
return this.response.getHeader(key)
}
setHeader(key: string, value: string): this {
if (this.response)
this.response.header(key, value)
return this
}
appendHeader(key: string, value: string, delimiter = ','): this {
if (this.response) {
const current = this.getHeader(key)
if (!current) return this.setHeader(key, value)
const newValue = [...current.split(delimiter), value]
.filter((el, i, a) => i === a.indexOf(el))
.join(delimiter)
this.response.header(key, newValue)
}
return this
}
setHeaders(dictionary: { [key: string]: string }): this {
if (this.response)
Object.keys(dictionary).forEach(key => this.setHeader(key, dictionary[key]))
return this
}
setStatus(code: number, message?: string): this {
if (this.response) {
this.response.statusCode = code
if (message)
this.response.statusMessage = message
}
return this
}
setNotFound(message = 'not found'): this {
if (this.response) {
this.response.statusCode = 404
this.response.statusMessage = message
}
return this
}
setError(message = 'internal server error'): this {
if (this.response) {
this.response.statusCode = 500
this.response.statusMessage = message
}
return this
}
}

Resources