![[tdq-boss1.webp|cover-picture]]
[[JavaScript]]で最も難易度が高く重要な項目、[[Promise (JavaScript)|Promise]]に入る前に立ちはだかる試練を乗り越えましょう。[[JavaScript]]前半戦の総復習です。
## Mission 1
#🙂NORMAL
以下の `animal.json` を生成するようなコードを書いてください。
- ファイル書き込みには[[Deno]]のメソッドを使う
```json
{
"animals": [
{
"id": 1,
"name": "ロバオ",
"age": 37
},
{
"id": 2,
"name": "みみぞう",
"age": 20
},
{
"id": 3,
"name": "セイキチ",
"age": 17
},
{
"id": 4,
"name": "タツヲ",
"age": 15
},
{
"id": 5,
"name": "マサハル",
"age": 4
}
]
}
```
%%
解答例
```js
const animals = {
"animals": [
{
"id": 1,
"name": "ロバオ",
"age": 37,
},
{
"id": 2,
"name": "みみぞう",
"age": 20,
},
{
"id": 3,
"name": "セイキチ",
"age": 17,
},
{
"id": 4,
"name": "タツヲ",
"age": 15,
},
{
"id": 5,
"name": "マサハル",
"age": 4,
},
],
};
Deno.writeTextFileSync(
"./animal.json",
JSON.stringify(animals, null, 2),
);
```
%%
> [!hint]- Hint 1
> [Writing files](https://docs.deno.com/examples/writing_files/)
## Mission 2
#😵HARD
[[#Mission 1]]で作成したファイルを読み込み、[[CSV]]形式の文字列に変換し、`animals.csv` として生成するコードを書いてください。
- 1行目はヘッダ
- 区切り文字はカンマ
`前提条件`
- 読み込むファイル名は **コーディング時点で決まっている** という前提でOK
- **[[@std.csv (Deno)|@std.csv]]などのライブラリは使わず** 自力で実装すること
- ファイル書き込みには[[Deno]]のメソッドを使う
%%
解答例
```js
import animalJson from "./animal.json" with { type: "json" };
const csvStr = `
id,name,age
${
animalJson.animals.map(({ id, name, age }) => [id, name, age].join(",")).join(
"\n",
)
}
`.trim();
Deno.writeTextFileSync("./animals.csv", csvStr);
```
%%
> [!hint]- Hint 1
> [[JSON]]ファイルの読み込みには[Importing JSON](https://docs.deno.com/examples/importing_json/)が便利です。
## Mission 3
#😱NIGHTMARE
[[#Mission 2]]で作成した `animals.csv` の情報をマスターデータとし、`GET /animals?minAge` で指定された `minAge` **以上** の `age` を持つ結果を[[JSON]]で返却するAPIサーバーを作成してください。
`前提条件`
- ヘッダの並び順は `id` `name` `age` で固定
- **[[@std.csv (Deno)|@std.csv]]などのライブラリは使わず** 自力で実装すること
%%
解答例
```js
const animalsCsv = Deno.readTextFileSync("./animals.csv");
const animals = animalsCsv
.split("\n")
.slice(1)
.map((r) => r.split(","))
.map(([id, name, age]) => ({ id, name, age }));
Deno.serve((req) => {
const url = new URL(req.url);
if (url.pathname !== "/animals") {
return Response.json({ "message": "Invalid path" }, { status: 404 });
}
const maxAge = url.searchParams.get("maxAge");
if (!maxAge) {
return Response.json({ "message": "No maxAge" }, { status: 400 });
}
return Response.json(animals.filter((x) => x.age >= maxAge));
});
```
%%
---
*NEXT* >> [[📗TDQ-021 エラーと例外処理]]