Skip to content
This repository has been archived by the owner on Jun 4, 2022. It is now read-only.

Backend fix #98

Merged
merged 33 commits into from
Mar 14, 2020
Merged

Backend fix #98

merged 33 commits into from
Mar 14, 2020

Conversation

kanade9
Copy link
Member

@kanade9 kanade9 commented Feb 20, 2020

今回ので直した箇所
swaggerの定義修正(exampleを追加してわかりやすくしました。)
update by made byを統一して edited byに。uidを返却
expressのインスタンスを一つに統一
star rtaing などをDBに突っ込む時に自動的に0にして格納する
class_dataエンドポイント修正
responseのステータスコード返却対応
ファイルの切り分けを行なった
requireをなくす→これは修正するとモジュールがありません等のエラーになるので対応していません。

cors対応はいらないっていう話だったのでやってないです。

Copy link
Member

@reud reud left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメント返しました〜


async function Verification(req: express.Request, resp: express.Response, next: () => void) {
// req.headers.authorization のオブジェクトが未定義となるためにts-ignore
// @ts-ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここのコメント消しておいてください (ts-ignore使われていた行は消えましたよね?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いや、最終的には消えませんでした。ので残しています

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここのts-ignoreはどこにかかっているのです?
image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ああ、21行目か・・・空行消しておいて欲しいかなぁ・・・

// @ts-ignore

// AuthorizationヘッダーはBearer <id_token>の形式のため、id_tokenを取り出すために7文字目以降の文字列を切り出している
const tokenstr = req.headers.authorization.toString().slice(7);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

iine


app.use(Verification);

export const WelcomeLog = functions.auth.user().onCreate((user) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これ何に使われているんでしたっけ・・・

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WelcomeLogとDeleteLogはユーザ登録と削除のデバッグ用に使ってます!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kanade9
多分また聞いちゃうのでそれがわかる様に変数名をかえていただけると!

return 0;
});

export const DeleteLog = functions.auth.user().onDelete((user) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これも何でしたっけ・・・

return 0;
});

// build multiple CRUD interfaces:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメント内容と表す行合ってない様な・・・

app.get('/comment', async (req: functions.Request, resp: express.Response) => {
console.log('subject_query= ' + req.query['class_name'] + ' uid=' + req.query['uid']);
try {
const qss = await fdb.collection('ClassSummary').doc(req.query['class_name']).collection('comment').doc(req.query['uid']).get();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こんな感じで縦に並べてかけるので見にくく感じてみたらこんな感じに書いた方が読みやすいと思う!

const qss = await fdb.collection('ClassSummary')
.doc(req.query['class_name'])
.collection('comment')
.doc(req.query['uid']).get();

}

const data = {
// nameは授業名です。titleはコメントのタイトル ex. 神授業です!!等
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いいね

'title': body.title,
'comment': body.comment,
'created_at': created_time,
'updated_at': moment().add(9, 'h').format(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

let class_created_time = null;
const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
if (doc.exists) {
class_created_time = doc.data().created_at;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class_created_time = doc.data().created_at || moment().add(9, 'h').format();

って短くかけるよ!doc.data().created_atに値が入ってたらそれが使われて、 がundefinedならmoment().add(9, 'h').format()が入る式になります。

try {
const qss = await fdb.collection('ClassSummary').doc(req.query['class_name']).collection('comment').doc(req.query['uid']).get();
if (!qss.data()) {
console.log('No comment were found match with ' + req.query['class_name'] + ' and this uid');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

文字列内展開がTypescript(JavaScript)に搭載されているので是非使ってください!

console.log(`No comment were found match with ${req.query['class_name']} and this uid`);

@kanade9
Copy link
Member Author

kanade9 commented Feb 23, 2020

ネスト消す方法でリファクタリングしてみたのですが[POST]api/class_dataで検証したところ、Error: Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.となり正しいパスを参照することができませんでした。.catch((e: string) => err = e);を削除してリファクタリング前の状態にしたところ正常に処理を完了することができました。

結論として、リファクタリングがうまくいかないみたいです。

@reud
Copy link
Member

reud commented Feb 24, 2020

@kanade9

リファクタリングがうまくいかない

了解です。
リファクタリング前とリファクタリング後のコード載せられますか?変更差分を追いたいのですが。
このコードならこうなるはずだけど、こうなってしまうみたいな情報が載ってると状況がすごく追いやすいです。

変更部分が分からないので有効ではないかもしれないですが、
All firestore set(doc) calls fail due to "Error:Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string" · Issue #320 · firebase/firebase-admin-node
こことかかもしれないですね

@kanade9
Copy link
Member Author

kanade9 commented Feb 24, 2020

https://github.com/gekko-org/pj-marowd/pull/98/files/6ef7dc229fc20779dd930ae482f1dd07eb4c5bce..82aa73eec7b9c8da0a4d347d855d8b3d9fb61fb4 
めちゃめちゃ比較わかりづらいんですが差分です。変更部分で大きなところはtry~catchをレビューされた方法で消して書き直した部分です。

参考サイトの記事読みました。documentのデータはjson型なのに、エラーでstring型を指定しているところに原因があるかもしれません。

@reud
Copy link
Member

reud commented Feb 24, 2020

@kanade9
URLに空白入ってるw (むしろどうやったんだこれ)
確認してみます。

Comment on lines 80 to 120
app.post('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;

// Check the validity of the token
const uid = admin.auth.decodedToken(body.token).uid;
if (!uid) {
resp.status(401).send('Unauthorized');
} else {
console.log(uid);
}

let class_created_time = null;
const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
if (doc.exists) {
class_created_time = doc.data().created_at;
} else {
class_created_time = moment().add(9, 'h').format();
}
const data = {
'name': body.name,
'faculty': body.faculty,
'department': body.department,
'fav_amount': body.fav_amount,
'grade': body.grade,
'professor': body.professor,
'is_random': body.is_random,
'rating': body.rating,
'term': body.term,
'edited_by': body.edited_by,
'created_at': class_created_time,
'updated_at': moment().add(9, 'h').format(),
};
try {
await fdb.collection('ClassSummary').doc(body.name).set(data);
console.log(data);
resp.status(200).send(JSON.stringify({'status': 'OK'}));
} catch (exception) {
console.log('An error occurred. Class data cannot add in database');
resp.status(500).send('Internal Server Error');
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

メモ

Comment on lines 72 to 115
app.post('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;

// Check the validity of the token

const uid = admin.auth.decodedToken(body.token).uid;
if (!uid) {
resp.status(401).send('Unauthorized');
return 0;
} else {
console.log(uid);
}

const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
const class_created_time = doc.data().created_at || moment().add(9, 'h').format();

const data = {
'name': body.name,
'faculty': body.faculty,
'department': body.department,
'fav_amount': 0,
'grade': body.grade,
'professor': body.professor,
'is_random': body.is_random,
'rating': 0,
'term': body.term,
'edited_by': body.edited_by,
'created_at': class_created_time,
'updated_at': moment().add(9, 'h').format(),
};
let err = "";
await fdb.collection('ClassSummary').doc(body.name).set(data).catch((e: string) => err = e);

if (err !== "") {
console.log('An error occurred. Class data cannot add in database' + err);
resp.status(500).send('Internal Server Error');
return 0;
} else {
console.log(data);
resp.status(200).send(JSON.stringify({'status': 'OK'}));
return 0;
}
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

memo

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kanade9 この辺見てるけど変更箇所として見る部分は合ってる?

参考サイトの記事読みました。documentのデータはjson型なのに、エラーでstring型を指定しているところに原因があるかもしれません。

これresponse送るところ(resp.status(500).send('Internal Server Error');)について原因があるのではないかっていう予想で合ってる?
見た感じ変更前と変更後で変わってない様な・・・・

@reud
Copy link
Member

reud commented Feb 24, 2020

@kanade9
なんか勘違いしてたらスマソン。CORSの問題があるからリクエストってどうなるんでしたっけ・・・?うまくいかない様な・・・?

if (err !== "") {
console.log('An error occurred. Class data cannot add in database' + err);
resp.status(500).send('Internal Server Error');
return 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kanade9
ふと思ったんですけど、ここ何故0返しているんですか?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

voidの認識なので return;で良いかと。原因の切り分けにもなるので変更お願いします

resp.status(500).send('Internal Server Error');
return 0;
} else {
console.log(data);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

early returnしているのでここのelseはいらないと思う!

@kanade9
Copy link
Member Author

kanade9 commented Feb 24, 2020

corsはローカルで実行するときは意識しなくて大丈夫
#98 (comment)
ここは1箇所でearly returnをすると、全部の箇所にreturnをつけろって怒られたのでそうしてます。

@reud
Copy link
Member

reud commented Feb 24, 2020

全部の箇所にreturnつけた方が良いのでは・・・

@reud
Copy link
Member

reud commented Feb 24, 2020

corsはローカルで実行するときは意識しなくて大丈夫

CORSはローカルでも意識する必要がある認識
localhostを共有対象に設定しなきゃいけないはず。

@reud
Copy link
Member

reud commented Feb 24, 2020

これは予想ですが、
kanadeがchromeを使ってないからlocalではcors対応していないとか・・・?
CORSエラー対策 - Qiita

@kanade9
Copy link
Member Author

kanade9 commented Feb 24, 2020

ごめん書き方が悪かったです。"ローカルでは意識しなくて大丈夫"じゃなくて、"PostmanとかCLIからHTTPリクエストを送るときには意識しなくても大丈夫"でした。
https://developer.mozilla.org/ja/docs/Web/HTTP/CORS

@kanade9
Copy link
Member Author

kanade9 commented Feb 24, 2020

"オリジン間リソース共有Cross-Origin Resource Sharing (CORS) は、追加の HTTP ヘッダーを使用して、あるオリジンで動作しているウェブアプリケーションに、異なるオリジンにある選択されたリソースへのアクセス権を与えるようブラウザーに指示するための仕組みです。ウェブアプリケーションは、自分とは異なるオリジン (ドメイン、プロトコル、ポート番号) にあるリソースをリクエストするとき、オリジン間 HTTP リクエストを実行します。"

今回検証している環境はWebアプリケーションを介していない場合なので、CORSが原因ではないと思われます

@reud
Copy link
Member

reud commented Feb 24, 2020

ごめん書き方が悪かったです。"ローカルでは意識しなくて大丈夫"じゃなくて、"PostmanとかCLIからHTTPリクエストを送るときには意識しなくても大丈夫"でした。
https://developer.mozilla.org/ja/docs/Web/HTTP/CORS

CLIからってことね了解です

@reud
Copy link
Member

reud commented Feb 24, 2020

"オリジン間リソース共有Cross-Origin Resource Sharing (CORS) は、追加の HTTP ヘッダーを使用して、あるオリジンで動作しているウェブアプリケーションに、異なるオリジンにある選択されたリソースへのアクセス権を与えるようブラウザーに指示するための仕組みです。ウェブアプリケーションは、自分とは異なるオリジン (ドメイン、プロトコル、ポート番号) にあるリソースをリクエストするとき、オリジン間 HTTP リクエストを実行します。"

今回検証している環境はWebアプリケーションを介していない場合なので、CORSが原因ではないと思われます

ブラウザ側が弾いているので私もその認識です。

@reud
Copy link
Member

reud commented Feb 24, 2020

@kanade9
made_byがswagger.yamlから消えているのにcloudfunctions側には残っているのでその辺りも統一した方が良いかな!
多分全置換(Ctrl + r) でさくっとできると思う!

@kanade9
Copy link
Member Author

kanade9 commented Feb 24, 2020

#98 (comment)
注目してほしい箇所は103,104行目あたりです
let err = "";
await fdb.collection('ClassSummary').doc(body.name).set(data).catch((e: string) => err = e);

@reud
Copy link
Member

reud commented Feb 24, 2020

@kanade9

await fdb.collection('ClassSummary').doc(body.name).set(data)の場合では正常に取得できています

エラーまとめられるしtry-catchにしましょう!理解足りてませんでした!ごめんなさい!

の様にエラー内容もconsole.logに出してくれると助かります!(すでにやってたらすいません)

try {
  const resp = await fetch(url);
  const json = await resp.json();
  console.log(json);
} catch (e: Error) {
  console.log("エラー発生!");
  console.log(e);
}

@kanade9
Copy link
Member Author

kanade9 commented Feb 25, 2020

ありがとう!!修正します!

@kanade9
Copy link
Member Author

kanade9 commented Feb 28, 2020

commentのパラメータ comment_uidについて。 uidはバックエンドで管理するため、なんらかの値が設定されていたら自分のコメントを持ってくるように処理を書きました。(値がセットされていない場合は全件のコメントを返す)

@reud
Copy link
Member

reud commented Mar 1, 2020

@kanade9
了解です!swaggerの該当部分のdescriptionにその仕様書いてくれるとありがたい!

@kanade9
Copy link
Member Author

kanade9 commented Mar 1, 2020

リファクタリング完了しました!修正箇所は
・パラメータの設定によって複数個のデータを返す部分の実装を修正
・exception をつけてエラーをわかりやすく!
・文字列展開の内蔵
・early return とreturn;を記載
・swaggerの仕様変更

@reud
Copy link
Member

reud commented Mar 4, 2020

@kanade9

リファクタリング完了しました!修正箇所は
・パラメータの設定によって複数個のデータを返す部分の実装を修正
・exception をつけてエラーをわかりやすく!
・文字列展開の内蔵
・early return とreturn;を記載
・swaggerの仕様変更

見逃してた!あざます!

@kanade9
Copy link
Member Author

kanade9 commented Mar 14, 2020

ヘッダーとリファクタリング終了したのでマージします

@kanade9 kanade9 merged commit 7ace2ee into feature/84_swagger_update Mar 14, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants