TypeScript TypeError和微服务问题

时间:2020-10-15 14:09:25

标签: javascript node.js typescript express microservices

所有人!

我现在正在学习一些微服务原理,并且我对收到事件时query_service中的错误有疑问

通常我的应用程序会创建一个帖子,用户可以在此帖子中发表一些评论,但是我不知道发生了什么,因此我尽一切努力在查询服务上解决此问题,因为当用户输入时,它会中断帖子中的评论

输出错误为:TypeError:无法读取未定义的属性“ comments”

我的路由器代码:

import { Response, Request, Router } from 'express';

const routes = Router();


interface IPost {
    id: string;
    title: string;
    comments: Comments[];
}

type Post = { [key: string]: IPost };
type Comments = { id: string, content: string };
interface IData {
    id: string;
    content: string;
    postId: string;

}

let posts: Post = {}

routes.get('/posts', (req: Request, res: Response) => {
    res.send(posts);
});

routes.post('/events', (req: Request, res: Response) => {

    try {
        const { type, data } = req.body;

        if (type === 'PostCreated') {
            const { id, title }: IPost = data;

            posts[id] = { id, title, comments: [] };
        }
        if (type === 'CommentCreated') {
            const { id, content, postId }: IData = data;
            posts[postId].comments.push({id, content});
        }
        console.log(posts)
        res.status(201).send({});
    } catch (error) {
        console.log(error)
    }
    
});

export default routes; 

其他一切都正常。 任何人都可以在这个问题上帮助我吗? 如果要查看整个程序,请查看项目的仓库:Microservice API

1 个答案:

答案 0 :(得分:0)

type等于CommentCreated时发生此错误,但是尚无带有给定postId的帖子。在这种情况下,您还应该先创建帖子(就像您对类型PostCreated所做的那样),例如;

if (type === 'CommentCreated') {
    const {id, content, postId}: IData = data;
    if (!posts[postId]) {
        posts[postId] = {id:postId, comments: []};
    }
    posts[postId].comments.push({id, content});
}

或者,如果要为不存在的帖子创建评论,则可以抛出错误而不是创建帖子:

if (!posts[postId]) {
    throw new Error("...");
}