フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

DDD/TypeScriptの勉強

ユースケース

Blogシステム-ユースケース.png (64.0 kB)

DDD

Blogシステム-Page-2.png (33.4 kB)

サンプルコード

class Blog {
    static _id: number = 1;
    id: number | null;
    categoryId: number | null;
    title: string | null;
    text: string | null;
    postDate: Date | null;
 
    constructor(categoryId?: number, title?: string, text?: string, postDate?: Date) {
        this.id = ((title) && (text)) ? Blog._id++ : null;        
        this.categoryId = categoryId ? categoryId : null;
        this.title = title ? title : null;
        this.text = text ? text : null;
        this.postDate = postDate ? postDate : null;
    }

    create(categoryId: number, title: string, text: string): Blog {      
      // リポジトリ作成してDB登録処理をする
      return new Blog(categoryId, title, text, new Date());
    }

    update(title: string, text: string): void {            
      // リポジトリ作成してDB更新処理をする
      this.title = title;
      this.text = text;
      this.postDate = new Date()
    }

    delete(): void {
      // DBの削除処理
      this.id = null;
      this.title = null;
      this.text = null;
      this.postDate = null;
    }
}

class Category {
    static _id: number = 1;
    id: number | null;
    categoryName: string | null;
    displaySort: number | null;
 
    constructor(categoryName?: string, displaySort?: number) {
        this.id = ((categoryName) && (displaySort)) ? Category._id++ : null;        
        this.categoryName = categoryName ? categoryName : null;
        this.displaySort = displaySort ? displaySort : null;
    }

    create(categoryName: string, displaySort: number): Category {      
      // リポジトリ作成してDB登録処理をする
      return new Category(categoryName, displaySort);
    }

    update(categoryName: string, displaySort: number): void {      
      // リポジトリ作成してDB更新処理をする
      this.categoryName = categoryName;
      this.displaySort = displaySort;
    }

    delete(): void {
      // DBの削除処理
      this.id = null;
      this.categoryName = null;
      this.displaySort = null;
    }
}

const category = new Category();
let categories: Category[]  = [];
categories.push(category.create('JavaScript', 1))
categories.push(category.create('Python', 2))
categories.push(category.create('Go', 3))
categories.push(category.create('PHP', 4))
console.log(categories)
const blog = new Blog();
const blog1 = blog.create(categories[1].id as number, 'Typescriptについて', 'Typescriptは')
console.log(blog1)

参考サイト

https://typescript-jp.gitbook.io/deep-dive/future-javascript/classes