【问题标题】:Problem with TypeScript TypeError and MicroservicesTypeScript TypeError 和微服务的问题
【发布时间】:2021-01-30 01:07:30
【问题描述】:

大家!

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

通常我的应用程序会创建一个帖子,并且在此帖子中用户可以放置一些 cmets,但我不知道发生了什么,我尝试了一切以在我的查询服务上解决这个问题,因为当用户制作时它会中断帖子中的评论

输出错误是:TypeError: Cannot read property 'cmets' of undefined

我的路由器代码:

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; 

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

【问题讨论】:

    标签: javascript node.js typescript express microservices


    【解决方案1】:

    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("...");
    }
    

    【讨论】:

    • 嗨,eol,感谢您的回复,但是,我不知道我的 cmets 数组有问题吗?这完全是问题所在,我尝试使用您在上面提出的一些提示,但我没有成功,仍然因同样的问题使我的 query_service 崩溃(例如)我创建了一个帖子,它看起来像这样:{'2888baff' : { id: '2888baff', title: 'Post 2', cmets: [] } },但是每次我尝试向这篇文章添加评论时,我都会收到相同的 TypeError ......你明白我的意思吗?跨度>
    • 您添加评论的请求是什么样的?它是否包含postId 的值2888baff
    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2017-04-27
    • 2021-06-05
    • 2020-11-14
    • 2021-07-02
    • 2022-01-22
    • 2021-11-19
    相关资源
    最近更新 更多