要らなくなった古いAngularプロジェクトを公開した


一人もくもく会 をリリースした当時、フロントはAngular2を使っていた。ただ、リリースしてすぐ下記の理由で使うのをやめた。

  • ちゃんとクローラが画面を解析できていなかった(詳しく調べてはないが多分クローラの場合だけエラーが出てたっぽい)
  • 一人でAngularはしんどすぎて無理

それでもいい勉強にはなったし、全く使ったことない人からしたら得るものもあるかもしれないので一応Githubに公開しておくことにした。(決してきれいなものではない)

https://github.com/dala00/mokumoku-front

リポジトリを見れば全部の情報はあるのだが、一応下記にいくつか特筆しておく。

共通ステートを扱うクラス

Angularを使っているとデータを適当に扱うと、変数などに入れてもちゃんとアプリケーションには反映されないので、ちゃんとAngularのライフサイクルに組み込むような管理クラスを作らなければならない。

なのでObservableやSubjectを駆使してクラスを作った。当時適当に試行錯誤して作ったので現在の正しいやり方とは違うかもしれない。

data.serivice.ts
import { Injectable } from '@angular/core';
import { Subject, Observable, Subscription } from 'rxjs';
import { User } from '../models/user';

@Injectable()
export class DataService {

  data: any[];
  private updateSources: any;
  private syncs: any;

  constructor() {
    this.data = [];
    this.updateSources = {};
    this.syncs = {};
  }

  set(key: any, value?: any) {
    if (value !== undefined) {
      const originalKey = key;
      key = {};
      key[originalKey] = value;
    }

    this.data = Object.assign(this.data, key);
    for (let currentKey in key) {
      if (this.updateSources[currentKey] != undefined) {
        this.updateSources[currentKey].next(key[currentKey]);
      }
    }
  }

  get(key: string | number) {
    if (this.data[key] == undefined) {
      return null;
    }
    return this.data[key];
  }

  sync(key: string | number, callback: (data: any)=>void) {
    if (this.syncs[key] == undefined) {
      const updateSource = new Subject<any>();
      this.updateSources[key] = updateSource;
      this.syncs[key] = updateSource.asObservable();
    }
    this.syncs[key].subscribe(result => callback(result));
    if (this.data[key] != undefined) {
      callback(this.data[key]);
    }
  }

  del(key: string | number) {
    delete this.data[key];
  }
}

WerckerによるCI

WerckerによるCIをしているのでそのサンプル。ただテストするだけではなく、カバレッジを取って適当なサーバーに送信して見れるようにしている。テストにChromeが使われるので、chromiumが入ったイメージをベースに作ったboxを使っている。

wercker.yml
box: dala00/chromium-xvfb-angular-cli

build:
  steps:
    - npm-install

    - script:
        name: npm list
        code: |
          npm list --depth=0

    - script:
        name: test start
        code: |
          ng test --single-run --code-coverage

    - script:
        name: echo nodejs information
        code: |
          echo "node version $(node -v) running"
          echo "npm version $(npm -v) running"

coverage:
  steps:
    - add-ssh-key:
        keyname: COVERAGE_KEY
        host: hostname

    - create-file:
        name: write key
        filename: $HOME/.ssh/id_rsa
        overwrite: true
        content: $COVERAGE_KEY_PRIVATE

    - script:
        name: Set permissions for ssh key
        code: chmod 600 $HOME/.ssh/id_rsa

    - script:
        name: Scp coverage html
        code: scp -o StrictHostKeyChecking=no -r coverage/* user@host:dir

デプロイスクリプト

deploy.js。ローカルで本番ビルドしたものをデプロイするプログラムを作っていた。ロールバックとかもできるようにしている。

まあ本来こんなのはCIで行うか、本番環境でビルドさせるものだと思うので必要ないと思うが。