簡體   English   中英

TypeScript TypeError 和微服務的問題

[英]Problem with TypeScript TypeError and Microservices

每個人!

我現在正在學習一些微服務原則,當我收到事件時,我對 query_service 中的錯誤有一些疑問

通常我的應用程序創建一個帖子,在這個帖子中,用戶可以發表一些評論,但我不知道發生了什么,我已經嘗試了一切在我的查詢服務上解決這個問題,因為當用戶發表評論時它會中斷一個帖子

輸出錯誤是:TypeError:無法讀取未定義的屬性“評論”

我的路由器代碼:

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:微服務API

type等於CommentCreated時會發生此錯誤,但還沒有具有給定postId帖子。 在這種情況下,您還應該首先創建帖子(就像您對PostCreated類型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("...");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM