bigmac-jp blog

web開発関連のメモ

JavaScript Fetch API メモ

JavaScript Fetch

Fetch APIはJavaScrtip標準のhttp通信の方法の1つ。
Fetch APIが導入される以前はXMLHttpRequestが一般的に使われいた。jQuery.ajaxXMLHttpRequestが使われている。
Fetch APIはPromiseオブジェクトをベースに設計されている。
非同期でhttp通信が可能なので、レスポンスが遅い処理の場合に関係ない後続処理を、シーケンシャルに実行可能。
Fetch API - Web API | MDN


// GET
function getTodoList(){

    fetch('http://localhost:3000/api/v1/list')
        .then(function(response){
            return response.json();
        })
        .then(function(myJson){
            myJson.forEach(function(value){
                if(value.done){
                    var tag = '<li>'+ value.title +'<li>'
                    $('#done').append(tag);

                    getTodoDetail(value.id)

                }else{
                    var tag = '<li>'+ value.title +'<li>'
                    $('#notyet').append(tag);
                }
            })
        })
}

//POST
function todoDone(data){
    
    fetch('http://localhost:3000/api/v1/done',{
        method: 'POST',
        headers: {
            "Content-Type": "application/json; charset=utf-8",
        },
        body: JSON.stringify(data),
    }).then(function(response){
        console.log(response);
    })
    .catch(error => console.error(error)
    );
}

動的テストと静的テスト

動的テスト
プログラムを実行してその実行結果のテストを行う。
実施方法
・テスターが試験仕様書をベースに、プログラムの実行しその結果をテストする。
・開発者がデバックモードでブログラムを実行し、プログラムの動作をテストする。
・プログラムを実行し、プログラムのパフォーマンスをテストする。


静的テスト
プログラムを実行しないで、ソースコード、ドキュメントの解析、テストを行う。
動的テストでは実行結果のみを確認するので、プログラムのロジックがブラックボックス化になりやすい。
静的テストではプログラムのロジックを解析するので、ロジックが明確になる。

実施方法
・プログラムレビューで第三者が、プログラムの内容をテスト、レビューする。
・静的解析ツールでプログラムを実行しないで、コーディングルールチェックを行う。

PHP メモ2 セッション

セッションIDがブラウザのcookieに登録されている過程を確認。


①アクセスするサーバにindex.phpを作成

<?php
session_start();
$_SESSION['name'] = '佐藤';

chromeのDevToolsのNetworkタブを開いとく。

③index.phpにアクセス。
"PHPSESSINID" : ufjp8mfm9shv9gnsmg6lkfk8fp がセッションIDとなる。("PHPSESSINID"はsession.nameのデフォルト値)
f:id:mtaryo:20190606203512j:plain

④サーバのセッションファイルディレクトリを確認
③で確認したセッションidに紐づくセッションファイルが作成されている。
sess_ufjp8mfm9shv9gnsmg6lkfk8fp

PHP メモ1 セッション

セッションファイルのパスの確認はphpinfo();で出力される。
f:id:mtaryo:20190605105314j:plain
session.save_path = /var/lib/php/session

デフォルトの設定は上記のパス(/var/lib/php/session)の配下にセッションファイルが作成される。

クライアントのブラウザ側でcookieにセッションidが登録され、サーバへのアクセス時にセッションidをもとにセッションファイルを読み込む。
cookieにセッションidがない場合は、新規のセッションファイルが作成される。

Git メモ2 コミットをまとめる

git rebase -iコマンドで複数のコミットをまとめる。

コミットの単位を細かくしている場合に、git logで履歴を確認するときに、logの粒度が細かすぎて履歴が見にくいことがあります。

例えば、「ユーザ一覧画面のCSV出力機能追加」の対応があったする。

開発時のローカル環境でのコミットの粒度は下記とする。(※適当です)
csvの出力処理
②ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整
csvの出力項目の変更対応
csv出力バグ対応

上記のコミットを"ユーザ一覧画面CSV出力機能追加"にまとめることにする。

コミットをまとめる前の状態を確認

$ git log
commit e3dd7083961d9c6dcddfs928893f0a2349a89jkdil1jkl (HEAD -> develop)
Author: aisutabetai <xxxxxxx@xxxxxxx.co.jp>
Date:   Thu May 31 15:13:29 2019 +0900

    csv出力バグ対応

commit 1378f176539a90f75sfaiiiowjkdls9978cd115db7b25a
Author: aisutabetai <xxxxxxx@xxxxxxx.co.jp>
Date:   Thu May 29 15:13:29 2019 +0900

    csvの出力項目の変更対応

commit 4325f07f68030b3422a2f1f092ffde651fsafddd111
Author: aisutabetai <xxxxxxx@xxxxxxx.co.jp>
Date:   Thu May 28 15:13:29 2019 +0900

    ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整

commit e51cbfjka899028j98jfklsa9f1aecdf7b883fec9b4fb5
Author: aisutabetai <xxxxxxx@xxxxxxx.co.jp>
Date:   Thu May 27 15:13:29 2019 +0900

    csvの出力処理

commit a199d24aa76f8f32fafjkla321jkl9kkljkdkslslslse (master)
Author: aisutabetai <xxxxxxx@xxxxxxx.co.jp>
Date:   Thu May 27 15:13:29 2019 +0900

    Initial commit

コミットをまとめる。

$ git rebase -i HEAD~4
#4つ分のコミットをまとめるの"HEAD~4"を指定。"~~~~"でも可能らしい。
#エディターが開く

pick e51cbae csvの出力処理
pick 5706e9a ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整
pick 1378f17 csvの出力項目の変更対応
pick e3dd708 csv出力バグ対応

# Rebase a199d24..e3dd708 onto a199d24 (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
~

4つ分のコミットが表示されている。
各コミットの頭に"pick"が表示されているので、"s"または"squash"に変更して保存。

pick e51cbae csvの出力処理
s 5706e9a ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整
s 1378f17 csvの出力項目の変更対応
s e3dd708 csv出力バグ対応

# Rebase a199d24..e3dd708 onto a199d24 (4 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup <commit> = like "squash", but discard this commit's log message
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
# .       create a merge commit using the original merge commit's
# .       message (or the oneline, if no original merge commit was
# .       specified). Use -c <commit> to reword the commit message.
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out


コミットをまとめたので、コミットメッセージもまとめる。

# This is a combination of 4 commits.
# This is the 1st commit message:

csvの出力処理

# This is the commit message #2:

ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整

# This is the commit message #3:

csvの出力項目の変更対応

# This is the commit message #4:

csv出力バグ対応

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Thu May 30 15:10:14 2019 +0900
#
# interactive rebase in progress; onto a199d24
# Last commands done (4 commands done):
#    squash 1378f17 csvの出力項目の変更対応
#    squash e3dd708 csv出力バグ対応
# No commands remaining.
# You are currently rebasing branch 'develop' on 'a199d24'.
#
# Changes to be committed:
#       new file:   csvOutput.php
#       new file:   userList.html
#


コミットのメッセージを修正&保存。

# This is a combination of 4 commits.
xxxxxxx-csv出力機能対応
・csvの出力処理
・ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整
・csvの出力項目の変更対応
・csv出力バグ対応

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Thu May 30 15:10:14 2019 +0900
#
# interactive rebase in progress; onto a199d24
# Last commands done (4 commands done):
#    squash 1378f17 csvの出力項目の変更対応
#    squash e3dd708 csv出力バグ対応
# No commands remaining.
# You are currently rebasing branch 'develop' on 'a199d24'.
#
# Changes to be committed:
#       new file:   csvOutput.php
#       new file:   userList.html
#
~


ログの状況を確認。1つのコミットにまとめられていることを確認。

$ git log
commit da7c22dd619b82c652c8895b78e845f571aac943 (HEAD -> develop)
Author: morita <moritary@capa.co.jp>
Date:   Thu May 30 15:10:14 2019 +0900

    xxxxxxx-csv出力機能対応
    ・csvの出力処理
    ・ユーザ一覧画面にcsv出力ボタンを追加&レイアウト調整
    ・csvの出力項目の変更対応
    ・csv出力バグ対応

commit a199d24aa76f8f3223c7b454d5401668053f4fee (master)
Author: morita <moritary@capa.co.jp>
Date:   Thu May 30 15:08:00 2019 +0900

    Initial commit

Git メモ1 git stash

git管理されているプロジェクトで追加機能を開発中(①)に、緊急で別のバグ修正(②)が発生した場合など、作業中の変更内容や追加ファイルを退避することができる。

作業中のファイルを退避

①の追加機能で下記のような変更、追加が発生。
・既存ファイルの変更
・新規ファイルの追加

上記の2ファイルを退避

# git stash save -u "2019/11/11 AAAA対応"

オプションの"-u"はaddしていないファイルも退避に含めることになります。"-u"なしの場合、更新されているファイルのみ退避される。
"2019/11/11 AAAA対応"のようにメッセージを追加することを可能。

退避した作業の一覧を確認
# git stash list
stash@{0}: On master: 2019/11/11 AAAA対応
退避した作業の詳細を確認
#git stash show stash@{0}
退避した作業を戻す
git stash apply stash@{0}
退避した作業を消す
git stash drop stash@{0}
Dropped stash@{0} (4c39e97c80b3396d1a86f43232323jkkkkkjj)

MySQL メモ11 複合index

複合indexのメモ。よくありがちな開始日付と終了日付を持つテーブルを範囲検索する場合に、indexを貼る。

下記SQLでテーブルを作成。

CREATE TABLE schedule (
  id int(11) NOT NULL,
  start_date datetime NOT NULL,
  end_date datetime NOT NULL,
  PRIMARY KEY (id)
)

とりあえず60件のデータを登録。

id	start_date	end_date
1	2014/01/01	2014/04/01
2	2014/02/09	2014/05/09
3	2014/03/20	2014/06/16
4	2014/04/28	2014/07/24
5	2014/06/06	2014/08/31
6	2014/07/15	2014/10/08
7	2014/08/23	2014/11/15
8	2014/10/01	2014/12/23
9	2014/11/09	2015/01/30
10	2014/12/18	2015/03/09
11	2015/01/26	2015/04/16
12	2015/03/06	2015/05/24
13	2015/04/14	2015/07/01
14	2015/05/23	2015/08/08
15	2015/07/01	2015/09/15
16	2015/08/09	2015/10/23
17	2015/09/17	2015/11/30
18	2015/10/26	2016/01/07
19	2015/12/04	2016/02/14
20	2016/01/12	2016/03/23
21	2016/02/20	2016/04/30
22	2016/03/30	2016/06/07
23	2016/05/08	2016/07/15
24	2016/06/16	2016/08/22
25	2016/07/25	2016/09/29
26	2016/09/02	2016/11/06
27	2016/10/11	2016/12/14
28	2016/11/19	2017/01/21
29	2016/12/28	2017/02/28
30	2017/02/05	2017/04/07
31	2017/03/16	2017/05/15
32	2017/04/24	2017/06/22
33	2017/06/02	2017/07/30
34	2017/07/11	2017/09/06
35	2017/08/19	2017/10/14
36	2017/09/27	2017/11/21
37	2017/11/05	2017/12/29
38	2017/12/14	2018/02/05
39	2018/01/22	2018/03/15
40	2018/03/02	2018/04/22
41	2018/04/10	2018/05/30
42	2018/05/19	2018/07/07
43	2018/06/27	2018/08/14
44	2018/08/05	2018/09/21
45	2018/09/13	2018/10/29
46	2018/10/22	2018/12/06
47	2018/11/30	2019/01/13
48	2019/01/08	2019/02/20
49	2019/02/16	2019/03/30
50	2019/03/27	2019/05/07
51	2019/05/05	2019/06/14
52	2019/06/13	2019/07/22
53	2019/07/22	2019/08/29
54	2019/08/30	2019/10/06
55	2019/10/08	2019/11/13
56	2019/11/16	2019/12/21
57	2019/12/25	2020/01/28
58	2020/02/02	2020/03/06
59	2020/03/12	2020/04/13
60	2020/04/20	2020/05/21

indexを貼る前に範囲検索を実行。

mysql> explain select * from schedule where start_date >= '2018/3/1' AND end_date <= '2018/10/1';
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | schedule | NULL       | ALL  | NULL          | NULL | NULL    | NULL |   60 |    11.11 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

typeカラムが"ALL"になっているため、フルテーブルスキャンになっていることがわかる。

start_dateとend_dateの複合indexを貼る。

mysql> ALTER TABLE schedule ADD INDEX index_start_end(start_date, end_date);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

複合indexを貼った後に再度範囲検索の実行計画を実行。

mysql> explain select * from schedule where start_date >= '2018/3/1' AND end_date <= '2018/10/1';
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
| id | select_type | table    | partitions | type  | possible_keys   | key             | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | schedule | NULL       | range | index_start_end | index_start_end | 5       | NULL |   21 |    33.33 | Using where; Using index |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

typeカラムが"range"になっているため、インデックスを用いた範囲検索になっていることがわかる。


webシステムの一覧画面で検索条件に"開始日付フォーム"と"終了日付フォーム"があって、入力されている場合検索条件に追加して、一覧の絞り込むを行う。
みたいな場合を想定。

①開始日付と終了日付が入力されている場合。 ※冒頭のSQLと同じパターン
開始日付:2018/12/1
終了日付:2019/4/1

mysql> explain select * from schedule where start_date >= '2018/12/1' AND end_date <= '2019/4/1';
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
| id | select_type | table    | partitions | type  | possible_keys   | key             | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | schedule | NULL       | range | index_start_end | index_start_end | 5       | NULL |   13 |    33.33 | Using where; Using index |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

②開始日のみ入力されている場合。
開始日付:2018/12/1
終了日付:null

mysql> explain select * from schedule where start_date >= '2018/12/1';
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
| id | select_type | table    | partitions | type  | possible_keys   | key             | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | schedule | NULL       | range | index_start_end | index_start_end | 5       | NULL |   13 |   100.00 | Using where; Using index |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

この場合もtypeカラムは"range"になっているので、indexが使われいる。


③終了日のみ入力されている場合。
開始日付:null
終了日付:2018/12/1

mysql> explain select * from schedule where end_date <= '2018/12/1';
+----+-------------+----------+------------+-------+---------------+-----------------+---------+------+------+----------+--------------------------+
| id | select_type | table    | partitions | type  | possible_keys | key             | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+----------+------------+-------+---------------+-----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | schedule | NULL       | index | NULL          | index_start_end | 10      | NULL |   60 |    33.33 | Using where; Using index |
+----+-------------+----------+------------+-------+---------------+-----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

typeカラムが"index"になっているため、フルインデックススキャンとなる。
複合indexの注意点としてindexの定義時のカラムの順番が重要となる。
今回の複合index(index_start_end )は、"start_date"、"end_date"の順番に定義した。
③のSQLの場合、条件に"start_date"がないため、複合index(index_start_end )が使われないことになった。


複合indexのカラム順番を逆にした複合indexを貼る。

mysql> ALTER TABLE schedule ADD INDEX index_end_start(end_date, start_date);
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

再度③のSQLを実行。

mysql> explain select * from schedule where end_date <= '2018/12/1';
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
| id | select_type | table    | partitions | type  | possible_keys   | key             | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | schedule | NULL       | range | index_end_start | index_end_start | 5       | NULL |   45 |   100.00 | Using where; Using index |
+----+-------------+----------+------------+-------+-----------------+-----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

この場合もtypeカラムは"range"になっているので、追加した複合index(index_end_start )が使われいる。