2024年4月の学習記録
4月の目標
AOJ
6問
213ページ ALDS1_8_A Binary Search Tree Iまで
--> 1_7_C まで
個人開発
DynamoDBにキャッシュを100件追加
DynamoDB, spotify search API とのなめらかな連携
簡潔なUIの完成
プレイリスト作成機能までつなぎこみ
--> DynamoDBにキャッシュは追加したものの、データ構造の変更を余儀なくされる
TiDBへの以降を検討中
簡潔なUIは作成済み、プレイリスト作成機能はまだ
Terraform / AWS
AWS 上で静的な Web サイトを公開しよう!
Amazon CloudFrontおよびAWS WAFを用いて エッジサービスの活用方法を学ぼう
上記2つをTerraformで構築
さらに、今のうちにクレジットを使ってドメインを取得する
teraform のポリシーを使ってcostのコントロール
--> AWS 上で静的な Web サイトを公開しよう!
に関してはTerraformで構築済み
ドメイン取得も完了
ポリシーでのコストコントロールは未完、他に優先すべき事柄があるため当分保留
lambdaでpackageごとnodeをデプロイする方法を検討中
web adapterの試用、AWS SAMの利用
AWS SAM を使ってテンプレートからサーバーレスな環境を構築する ハンズオン完了
Frontend Mentor
掲載されている残り2つのプロジェクトを完遂させる
--> Learning Path に従って学習することに
代わりに以下の2つのプロジェクトを完遂
Next.js
Next.js の以下公式ドキュメント読了
data fetching * 3 rendering * 4 testing * 2 authentication route-segment-config form の実装例 next.js security
--> authenticationまで読了
MDN CSS
→一旦 テキストの方向 までとして、CSSレイアウトの50%読了を目指す
--> そろそろ飽きてきた&文章が読みづらいので挫折
レイアウト編をピックアップして読了&個人のQiita記事で代用
記録
4/30
AOJ
ALDS1_7_D
木の復元
個人開発
Grafana, prometheus も自動で作られ、モダンなダッシュボードもある
optimistic transaction, pessimistic transaction の2種類
transaction isolation levels について
アプリケーション側の責任でのリトライ、エラーハンドリングなど
optimistic transactionが何なのか知らない場合は、伝統的なpessimisticを使うべき
sqlのcommit とは何なのか
トランザクション独立レベルとは何なのか
次回
Terraform / AWS
元々、iam roleの作成にはassume roleの指定が必要
Trust policy として作成している
何のサービスに対するroleを作るか?というところでpolicyが変わる
それからpermissionsで AmazonDynamoDBFullAccess を与えたりなど
permissions boundary とは何なのか?
特定のユーザーがロール作成するのを許可しつつ、権限昇格を防止する
iam管理者委任などで便利らしい
既存のコードだと、index.tsの変更を検知してくれない
色々と問題がありすぎるので、これやめたほうが良さそう
lambda web adapterの例を参考にしたほうが良くないか?
次回
以下ページの方法を参考にもう一度ゼロからトライする
Frontend Mentor
次回こだわりポイントを明文化、他人のコードとの比較
Next.js
Data Transfer Object
canSeeUserName のような関数を用意して現在のユーザーが取得可能かどうかを判定させる
Layoutでデータフェッチする必要がある場合は、Layoutで認証をするのではなく、
データソースに出来る限り近い場所で認証を行う。フェッチする関数の中で認証する
server actionはpublic APIのごとくきちんと認証すること
次回 next security
MDN CSS
grid 解説記事
各アイテムでtrackの番号を振って配置する方法、
container部分でアスキーアートのように指定する方法の二つがある
grid-auto-rows で事前に指定した分の長さをはみ出したコンテンツの縦の長さを決められる
次回 自動的に配置 から
4/29
type-challenge/leetcode
サブクエリ不要
union に対して in を使うことでdistributeにオブジェクトが定義できたりする
In TypeScript 4.1 and later versions, the as keyword can also be used in mapped types for remapping key names. This allows you to change the names of keys when creating new types.
新しいマップ型を作成する際にasを使うことでキーの名前を変更できる
要するに、asで変更できるのはmapped typeのkeyにあたる部分の模様
なぞのintrinsic keyword
個人開発
cockroach db + react example
情報量の多さ、日本での採用事例の多さを考慮するとTiDBで構築するほうが良さそう
料金もcockroachDBと変わらない
AWSとの相性も良さげ
DMMでの採用事例もある
次回
以下読む
必要なところを理解したら以下でチュートリアル
Terraform / AWS
あくまでTerraformは既存のファイルをクラウドとどう通信するのか、を決定する
統合的なコマンドはyarnに任せるパターン
assume role とは何か?
やはりassume roleがよくわからない。EC2のときはどう記述すればよい?
iam roleに記述する場合と、assume roleに同じlambdaのアクセスを許可する場合でなにが違う?
次回
Terraform で構築したリソースをいじってTerraformがどのように実際のリソースに影響するか調べる
4/27
type-challenge/leetcode
sum(if())構文で簡単
Push
unshift
parameter
type MyParameters<T extends (...args: any[]) => any> = T extends (...args: infer params) => any
? [params]
: never
// 関数のパラメータを上記の形式でinferすると、例えば以下の例では[[arg1: string]]が取得できる
function hoge(arg1: string): void { }
type a = MyParameters<typeof hoge>
get return type
Function型というのもある
個人開発
次回
cockroach db と vercel でNext.js アプリを作るチュートリアルTerraform / AWS
zipでlambdaをアップロードする方法
-
aws_lambda_function でlambdaを作成
s3にコードをアップロードする方法
s3_key ってなんだっけ?
オブジェクトから取得したkey を指定すればよさげ -
aws_s3_bucket で空のbucketを作成
-
null_resource でローカルでビルドを行う
npm install, build
aws s3 cp
s3_bucket_server_side_encryption_configuration とは?
サーバーサイドの暗号化設定についてこんな面倒なスクリプトをくまなくても出来る方法はありそうなもの。
次回
かなり丁寧な解説付き。
シンプルなスクリプトで解決している
4/26
AOJ
type-challenge/leetcode
- Typescriptの Equal util type について詳細
https://zenn.dev/yumemi_inc/articles/ff981be751d26c
要するに、Conditional type そのもの同士の比較を行った際に
コンパイラ内部で型の正確な比較が行われる、ということ
Terraform / AWS
こちらを参考に構築
null resource とは?
指定したコマンドを実行するためのリソース
何もプロビジョニングしない
triggers を設定することでどんなときに発火するか決める
fileset パターンに一致する複数のfile名の配列を返す
次回 全行にコメント解説を書く もしくは口頭説明
Frontend Mentor
flexと一緒に使うのは justify-content
gridと使うのはjustify-items
Next.js
セッションを複合してユーザーidを取得
dbにアクセスしてユーザーidからユーザー情報を取得する
middlewareとの役割の違いは?
sessionが正しく保存されているかどうか
DALは具体的にユーザー情報をDBから引き出すような用途
次回 server componentsから
MDN CSS
#container {
display: grid;
grid-template-rows: 100px 50px;
grid-template-columns: 150px 1fr;
}
まずこれらのプロパティで 行の高さ、列の幅を決める
150px と 1fr が共存しているとき、 frは残り全部 という意味になる
もちろんfrの単位の考え方は活かされる
ラインの番号でアイテムの配置を決定する方法と、アスキーアートのようにエリアに名前をつけて指定する方法がある
後者をtailwindcssで使うにはどうすればよい?
次回
Tailwindcssではgridをどのように扱っているのか
場面別編
4/25
type-challenge/leetcode
配列に対してkeyofを呼んだら?
type c1<T> = {[P in keyof T]: P}
type cc1 = c1<[{hoge: string, fuga: number}, 2, 3, 4, true, string]>
"1", "2" とかが返ってくる
配列も広義でオブジェクト?
type Includes<T extends readonly any[], U> = IsEqual<{
[P in keyof T as T[P] extends U ? 0 : never]: T[P]
}, { 0: U }>
genericsの中で使う型Tのことを 型パラメーター type parameter とよぶ
genericsでは、asであり得なさそうな型変換も出来る
type a1<T> = {
[P in keyof T as never]: T[P]
}
type ac1 = a1<[1, 2]>
T as string
のような型変換は不可能
下記はエラーになる
type f1<T> = { [P in keyof (T as (0 | 1))]: string }
keyofが結びついているのはあくまでその直後の型まで
下記で、b1とd1は等価
つまり、asによって型推論されるのはstringの部分ではなく (keyof string) の部分
type b1 = { [P in keyof string as 0 | 1]: string }
// --> { 0: string, 1: string}
type c1 = { [P in keyof (0 | 1)]: string }
// --> { toString: string; ... }
type d1 = { [P in (0 | 1)]: string }
// --> { 0: string, 1: string}
type g1 = { [P in (keyof string) as (0 | 1)]: string }
// --> { 0: string, 1: string}
型定義の中でasが使えるのは、keyofによるもの、かつ配列のキー指定の場所 だけの模様
個人開発
cockroach db をlinux localで使う方法
string similarity などを使って単語の類似度を測る
Terraform / AWS
node_moduleが必要な関数をlambdaで実行するにはどうすればよいのか?
次回これを一通り手を動かしてみる
Next.js
authorizationの方法
optimistic
cookieを使う方法
UIを表示するか否か、ロールによってユーザーをリダイレクトするか否か
secure
databaseに格納されているセッションデータを使う方法
センシティブなデータへのアクセスが必要となるケース
セッションを格納した後、どうやってサーバー側でチェックする?
optimistic checkであれば、middlewareでcookieを受け取って行う
全てのrouteで使われるので、部外者を弾きやすい
ただ、これがデータを守るための唯一のディフェンスラインになってはならない。
次回 data access layerから
MDN CSS
公式の説明だと正直なにがなんだか全然わからないので別のサイトを参考にする
次回は以下を読んで理解を深める
4/24
AOJ
参照返しの関数で参照で受け取りを行うとコピーコンストラクタが使われなくて済む
個人開発
LibROSA: Pythonで曲の特徴抽出や類似性比較を行うためのライブラリです。音楽解析や機械学習にも利用されます。
Echo Nest Remix: Echo NestのAPIを利用したPythonライブラリで、曲のビートやキー、テンポなどの解析が可能です。
Essentia: C++で曲の特徴抽出を行うライブラリで、PythonやMATLABなどの言語からも利用可能です。
AcousticID: 音響指紋を利用して曲の一致を判定するライブラリで、MusicBrainzと連携しています。
Deezer API: Deezerは音楽ストリーミングサービスで、APIを介して曲のメタデータや音響指紋を取得できます。Node.js向けのDeezer APIクライアントがあり、これを使用して曲の一致を判定できます。
MusicBrainz API: MusicBrainzはオープンな音楽データベースで、APIを介して曲のメタデータを取得できます。Node.js向けのMusicBrainz APIクライアントがあり、これを使用して曲の一致を判定できます。
AcousticID API: AcousticIDは音響指紋を利用して曲の一致を判定するサービスで、APIを介して利用できます。Node.js向けのAcousticID APIクライアントがあります。
色々なネットサービスがある
MusicBrainz も曲名に関する情報が載っていいてAPIもあるので分析に使えそう
Terraform / AWS
余計なiam role, policyが作成されるので、まとめて削除しておく
次回
lambda関数の作成とevent scheduleの作成をまた1から
Terraformで同じものを構築し直す
TaskChuteの更新関数をnodeで実装する
4/22
type-challenge/leetcode
世にも奇妙なboolean型
boolean = true | false 説?
検証している記事があった
type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
? V extends U
? true
: Includes<W, U>
: string
type foo = Includes<[boolean], false>
実際、foo型は true | string になる
? V extends U
の時点で、 (true | false) extends false
になっているとすると、2回それぞれに対してextendsが判定され、一方は再帰しfalseを返し、
一方はtrueとして変えるためunion typeになる
type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
? [V] extends [U]
? true
: Includes<W, U>
: false
タプル化すると望み通りの挙動になる
distributive な挙動を見せるのはgenericsのときだけ
type bar<T> = T extends 1 ? true : false
type b = bar<1 | 2> // --> boolean
type hoge = (1 | 2) extends 1 ? true : false // --> false
個人開発
whereが便利に使えない
勝手にGraphQLサーバーを作ってくれるスグレモノ
Terraform / AWS
何かAWS上のサービスで同じバス内のイベントが発生した際、条件を満たすかチェックされる
イベントグループみたいなもの?
event archiveを作成すると、managedなevent ruleが作成される
Event Bridgeとは?
AWS policy
principal 許可を与える対象、もの
resource ポリシーで取り扱う対象、たとえばS3のオブジェクトとか
誰に対して(principal)、なに(resource)に対する操作(action)を許可(Effect: allow)するか?
どんなときに?(Condition)
次回 lambda関数のスケジュール
Next.js
stateless session の作り方
- シークレットキーを作る(署名、復号に使う)
- sessionを暗号化、復号するロジックを作る encrypt 関数の引数としては、userId, expiresAt などを渡す
- cookies() を使ってクッキーの管理を行う
次回 database sessions
MDN CSS
.container {
display: grid;
/* grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); */
grid-template-columns: repeat(2, 1fr); // 1fr は画面分割単位 2列を配置するということ
grid-auto-rows: minmax(100px, auto); // カードの高さは最小で100px, コンテンツが肥大したら自動で拡大する
gap: 20px;
}
.container {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
横方向 最低200px, 最大で1単位
auto-fit でこれらの基準を満たしながら、配置される数が変化する
200px ~ 1fr とはどういう意味なのか?
次回
収まる限り多くの列 から
4/21
type-challenge/leetcode
left join するだけの簡単な問題
なぜEqualが動作するのか?
type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
? V extends U
? true
: Includes<W, U>
: false
type foo = Includes<[boolean], false>
なぜこれがワークしないのか?
なぜ、foo typeはbooleanになってしまうのか?
TypeChallengeのdiscordがあったのでここで質問してみる
さらに沢山の独自 utility type を集めたもの
Terraform / AWS
sam init で対話的にsamプロジェクトを初期化出来る
sam buildでtemplateを作成
sam deploy --guided
で対話的にデプロイ出来る。スタックの名前とかも決められる
sam local start-lambda
sam local start-api
などでデプロイする前にローカルで検証可能
eventbridge を使えば、タスクをスケジュールして実行することが可能
次回
チュートリアルを簡単にこなすeventbridge + lambda でtaskchuteの雑務タスク自動追加
Frontend Mentor
listに振られる連番の色の変更は
marker:text-orange-900 などで行う
marker:font-bold など
そこまで細かい調整はできない
Next.js
useFormStatus を使う場合は、 formタグの中で使う。
-
capture user credentials
formでパスワード、メールなどをFormState型で受け取り、サーバーアクションに渡す -
validate form fields on the server
サーバー側で、Zodなどを使ってバリデーションを行う -
create a user or check user credentials
問題があればエラーを表示
セッション管理ライブラリ
library such as iron-session or Jose.
次回 Stateless Sessions
MDN CSS
flex: 1 auto
について
最初のサイズを保持しつつも、画面幅をできるだけ満たそうとする
次回 グリッドから
その他
4/20
type-challenge/leetcode
2種類の extends を上手く使えれば簡単
infer を使った冗長な回答
type Concat<T extends readonly any[], U extends readonly any[]> = T extends readonly [...infer V]
? U extends readonly [...infer W]
? [...V, ...W]
: never
: never
これでよい
type Concat<T extends readonly any[], U extends readonly any[]> = [...T, ...U]
型安全なany型
型を絞り込まなければ、unknown型を別の変数に代入することができないし、メソッド呼び出しもできない
ifによって型を絞り込むことで、Typescriptが安全だと判断してエラーを出さずに関数を実行できたりする
typeof instanceofを使って型ガードが出来るが、それ以外にも独自に型ガード関数を定義することができる
zod, superstructなどのライブラリを使うと、沢山のプロパティのチェックを簡単に行える
個人開発
引き続きUIの整備
spotifyのUIを見倣う
Terraform / AWS
DynamoDBテーブル作成, lambda連携
AmazonDynamoDBFullAccess のポリシー名が DynamoDBFullAccess となっていたためずっとエラー
次回 sam CLIのハンズオンから
Frontend Mentor
w-96がMAX?
max-w-lg とかを使うとより大きな画面幅を実現できる
max-width とwidth ってなにが違うのか?どういうときに使い分ける
Next.js
基本はauthentication libraryを使うことが推奨されている
全然わからない
MDN CSS
一括指定対個別指定から
orderを指定して、若い方から先に表示させることも出来る
flexboxについてわかりやすい例
次回 ネストしたフレックスボックス から
grid と flexの違いについてわかりやすい
その他
AppImage をubuntuランチャーから起動する方法
要するに、/usr/share/application か ~/.local/share/application のどちらかに *.desktop を作成すればよい4/18
AOJ / type-challenge
Utility typeについて
再帰で高さを求める
個人開発
tailwindcss prettier の利用
.prettierrc.ymlで、以下のように書く
plugins:
- prettier-plugin-tailwindcss
個人開発で色々気をつける点まとめ
SEOについても
Terraform / AWS
lambda の出力フォーマットについて
Events以降で指定するできるパラメータについて
Frontend Mentor
tableの中に直接文字とかを入れていると駄目っぽい
Next.js
こちらを参考にvitestを導入
まずReact Testing Library の理解が必要になりそう
その上でVitestを利用する利点は?まとめて実行など?
Next.js の公式実例
https://github.com/vercel/next.js/blob/canary/examples/with-vitest/tests/Home.test.tsx
次回 testは一旦先送りにするとして、authenticationの実装について
authenticationMDN CSS
垂直方向にマージンが重なると、総裁が起きて大きい方のマージンのみが適用される
あまり使わなそうだが、 flex-direction: row-reverse とかを指定したり出来る
flex: number
を指定することで、要素ごとにどれだけの主軸に対して幅を使うかの割合を表示できる
mdnでは以下で見られる
Tailwindでの対応は以下
次回
flex: 一括指定対個別指定
4/17
type-challenge/leetcode
extends any とは何なのか?
conditional typesで展開するために便宜的に使っている模様
then メソッドを持っているオブジェクトのこと
個人開発
突然ですが、ここで Typescriptの型システムについて、中上級者向けのクイズを出題します。
graphql-codegen などで、APIのクエリから型定義を自動生成できたりする。
例えばこんな感じで、ListQuery
型が自動生成される。
type ListQuery = {
__typename?: "Query";
MediaListCollection?: {
__typename?: "MediaListCollection";
lists?: Array<{
__typename?: "MediaListGroup";
entries?: Array<{
__typename?: "MediaList";
media?: {
__typename?: "Media";
id: number;
title?: {
__typename?: "MediaTitle";
native?: string | null;
romaji?: string | null;
english?: string | null;
} | null;
coverImage?: {
__typename?: "MediaCoverImage";
extraLarge?: string | null;
large?: string | null;
} | null;
} | null;
} | null> | null;
} | null> | null;
} | null;
};
type MediaArray = {
__typename?: "Media";
id: number;
title?: {
__typename?: "MediaTitle";
native?: string | null;
romaji?: string | null;
english?: string | null;
} | null;
coverImage?: {
__typename?: "MediaCoverImage";
extraLarge?: string | null;
large?: string | null;
} | null;
}[];
開発をしていると、こんな感じで部分的に型を抜き出したくなるようなことがある。
もちろん、こうやって型を抜き出してコピペして自前で定義して使ってもよい。
しかし、他人が作ったAPIから自動生成した型ListQuery
は、APIの仕様変更で
attributeが増えたり減ったり、あるいはネスト構造が変化するかも知れない。
その度に自前で定義した型を再定義しないといけないのは、非常に面倒。
どうにかして、ListQuery
のみをsingle source of truth として
MediaArray
型をエレガントに生成することはできないだろうか?
但し、APIの仕様が変わったりしたとしても
__typename?: "Media"
というattributeは
必ず持つという仕様は変更されないとする。
私はこの問題について真に驚くべき解法を発見したが、ここに記すには余白が狭すぎる。
Terraform / AWS
アイデンティティベースのは、IAMやロールにつけるやつ
iamのポリシー画面に入力されているのと同じ文字列を入れればOK
次回 API gateway, dynamoDB連携 & SAM CLIダウンロード
Frontend Mentor
flex と gap を組み合わせることで、ボックス内で要素を並べる時に空白を指定できる
これとmx-autoを使ってformatする方法がある
mx-autoは一つのコンテンツにしか適用できないので、複数のカードがあったりしたら全部揃えるのに
全部にmx-autoを指定しないといけない
個人的には justify-center, items-center を使うべきと考える
Next.js
middlewareのために使われるランタイム
使えるAPIが限られている
どのコードがサーバーで実行されるべきで、クライアントで実行されるのかをしっかり理解することが重要
次回 Testing
MDN CSS
position:
- relative
本来その要素があるべき位置から、ずらす - absolute
ページの一番上から、ずらした位置に配置する
要素はその場所になかったものとして扱われる - fixed
画面上に固定されたように見える - sticky
特定の場所までスクロールすると、fixedと同じような動作になる
表の一番上のカラムだけ残したいときとか、便利そう
次回通常フローから
4/16
AOJ
const map では、operator[] は使えないので代わりにatを使う
関数テンプレートを使って、任意のtypeのinputを行う関数を作りconstでcinできるようにする
個人開発
vscodeの特定のsnipetを無効にしたい
class スニペット
classNameを入力しようとしていつも間違える
特定のsnipetのオーバーライドは難しい模様
flex flex-row, flex-col を駆使して一定の表形式で要素を並べられるように
Terraform / AWS
AWS SAM handson
sourceファイルにはローカルパスを指定して良い
aws cloudformation package
することでzip化されたコードが指定されたs3にアップロードされて、適切なpathに変換される
以下の記述をyamlに足すことで、cloudformationがsamの拡張記法を使えるようになる
Transform: AWS::Serverless-2016-10-31
Resources:
TranslateLambda: # 関数名
Type: AWS::Serverless::Function # lambdaのこと。
Type: AWS::Serverless::Function 以外にも、下記に指定した様々なリソースが使える
# package
aws cloudformation package \
--template-file template.yaml \
--s3-bucket *your-backet-name* \
--output-template-file packaged-template.yaml
# deploy
aws cloudformation deploy \
--template-file ./packaged-template.yaml \
--stack-name hands-on-serverless-2 \
--capabilities CAPABILITY_IAM
--capabilities CAPABILITY_IAM
が必要なのか
→結局よくわからない。IAMリソースを作成する場合があるとき、とあるが作るのはlambdaではないのか
Failed to create/update the stack. Run the following command
to fetch the list of events leading up to the failure
aws cloudformation describe-stack-events --stack-name hands-on-serverless-2
なんか作成が上手く行かない
cloudformation のマネージメントコンソールに行く
python3.7がサポートされていないことに起因するエラーの模様
一旦stackを削除して、packageしなおして、s3にアップロードし直して再度トライする
完了
iam policyとかがどうなっているのかと思ったら、自動で作成されている
lambdaのconfiguration, view role documentから確認可能
Frontend Mentor
カスタムプロパティを利用
bg-[color:hsl(0,90%,90%)]
frontend mentor 提出
Next.js
React cache function
App router で使ってみる
cache は、サーバコンポーネントでのみ使用できます。
RSCのことも指しているので、おそらく'use client'以外では使える
cacheの引数に指定するものがプリミティブでないもの、例えばオブジェクトなどは
毎回作成するような形だと別のものの参照だと考えられてキャッシュがヒットしない
上記はcacheのテストを行ったもの
次回
edge runtimesについてMDN CSS
ブロックの方向 横書きモードでは、下方向
インライン方向 `` 右方向
grid と flex の違い
flex は一次元的な制御、gridは二次元的な制御
昔はfloat を使ってflex grid の代用をして段組みレイアウトを組んでいたらしい
floatの使いみちがわからない
次回 位置指定のテクニック から
4/14
AOJ
ALDS1_7_B
再帰関数を使って木の深さ、高さを調べる
高さ => 葉までの再長距離
再帰関数が書けるようになってきている
個人開発
dynamodbのクエリ結果を安全に扱う方法について
ReturnTypeというユーティリティタイプがあり、関数をgenericsに指定すると戻り値が取得できる
type BatchGetParams = ReturnType<typeof convertToBatchGetParams>;
凝集度とは?復習
結合度の話
Terraform / AWS
zip と docker でlambda web adapter を比較してみたベンチマーク記事
Non-AWS base images may be used since the Runtime Interface Client ships with the Lambda Web Adapter.
COPY /lambda-adapter /opt/extensions/lambda-adapter
どんなイメージでも、常軌を追加するだけで使える模様
alpineは安定性の観点から使わないほうが良いとのこと
golangじゃないと難しそう?
マルチステージビルドで、nodeのパッケージが更新された場合とかは再度イメージビルドしないと駄目?
node.js のモダンなdocker構成について
Frontend Mentor
box-shadow の作り方について
box-shadow: x-offset, y-offset, 色
を指定する
3つのsize関係の引数があった場合、ぼかし半径を決められる
tailwindではarbitrary value で以下のように
shadow-[10px_10px_black]
transition クラスでhover時などの動作をtransitionに出来る
transition-shadow
transition-color
など、対象を限定することも可能
learning path にしたがって進むのも良さそう
次回 READMEの改訂とpublish
Next.js
fetch以外を使うときは、cacheを使うべし
これはサーバーサイドでも使えるのか?
npm i server-only
でインストールすることで、'server-only' が記載できるように成り、
これがclient側でimportされたりするとbuild time error が発生する
→あとで実際に試す
同様にclient-onlyもあるらしい
実験してみた。
import 'server-only'
が記載されているファイル上のサーバーアクションを、'use client' 宣言されている
componentで使うと以下のようなエラー
One of these is marked as a client entry with "use client":
./app/dashboard/customers/serverOnlyFn.ts
./app/dashboard/customers/page.tsx
⨯ ./app/dashboard/customers/serverOnlyFn.ts
ReactServerComponentsError:
You're importing a component that needs server-only. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
Learn more: https://nextjs.org/docs/getting-started/react-essentials
モダンな設計パターンについてと、NextApp routerでそれを実現する方法について
次回
Reactのcache関数を試す
MDN CSS
margin-top は margin-block-start にマップされ、
padding-left は padding-inline-start にマップされる
これによってテキストの方向によらず一貫して描画が出来る
次回から 要素のはみ出し を飛ばして CSS layoutに入る
4/13
type-challenge/leetcode
list of product
type-challenge
distributive conditional types と呼ばれる
そのため、以下の意味が一見不明なtypeでは、
type MyExclude<T, U> = T extends U ? never : T
union型の|で区切られたそれぞれについて評価される
そろそろinferを理解する
conditional type としての
extends の右辺につけることができる
T extends (infer U) => string ? U : never
引数の型を取り出せる
type First<T extends any[]> = T extends [infer A, ...infer rest] ? A : never
このように残りの不定数の引数を表すようなことも可能
型条件分岐の中でまさか再帰を行うことになるとは...
個人開発
failed to satisfy constraint: Member must have length less than or equal to 100
BatchGetCommand では、最大で100件のクエリまでしか検索できない
2重配列を作って、100件ずつクエリする
Terraform / AWS
docker で next.jsのマルチステージビルドを行う場合のプラクティス
nextjs を web adapter で起動する例
lambda関数は最大で15分実行可能
Frontend Mentor
blog-preview-card-main
この程度の簡単なレイアウトなら何も見なくてもある程度作れるようになった
わからないところだけ参考サイトのを見て学習すれば良さげ
Next.js
However, "use client" doesn't need to be defined in every component that needs to be rendered on the client. Once you define the boundary, all child components and modules imported into it are considered part of the client bundle.
use client を使っているファイル内でimportするコンポーネントは全てclient componentになるってことか?
client component の中でSuspenseを使っても意味がない?
Next.js はreact APIを使って、static HTMLを生成する機能を使っているので、最初のページロードは
server component, client component ともにクライアントがparseしたりダウンロードしなくていい
次回 composition pattern
client, server componentの連結パターン色々MDN CSS
vertical-rl: 右から左へのブロックの流れの方向。文は垂直に実行されます。
vertical-lr: 左から右へのブロックの流れの方向。文は垂直に実行されます。
違いがわからない
rl 縦書きで、右から左に文章が配置される
書き込みモードが縦になると、ブロックの方向は横になり、インラインの方向は縦になる
height, width の設定方向は変わらないので(物理)、論理的なバージョンに置き換えることで両対応できる
次回以下から
その他
デバッグ時エラーの解決方法
それでも1個のエラーだけは残って気持ちが悪い
remoteRoot, localRoot を設定している場合は設定不要ぽい
4/12
AOJ
ALDS1_7_B
二分木の高さ
個人開発
テスタビリティのため、BatchGetCommand のためのparameter整形は別関数で実施
リクエストのやりとりは別の関数の責務とする
Terraform / AWS
bucketポリシーの削除、public access blockの設定でs3への直接のアクセスは禁じられるが、
これだとCloudfrontからもアクセスできない模様
X-Cache: Error from cloudfront
が返ってくる
そもそもoriginってなんだっけ?
S3など、コンテンツ提供元のこと
origin access controle を作って、s3のbucket policyを変更する必要がある
どんなpolicyをコピースべきかはコンソールで教えてくれる
特定の条件の時にのみポリシーが適用されるように出来る
condition-key で、AWS:SourceArn 、 aws:username などを指定する
それぞれのサービスには固有のコンテキストキーがあるので、それを利用する
terraform では、variableがこれに相当する
oac の設定値について参考
AWSからs3に設定するように渡されたjson
{
"Version": "2008-10-17",
"Id": "PolicyForCloudFrontPrivateContent",
"Statement": [
{
"Sid": "AllowCloudFrontServicePrincipal",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::anitunes.click/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::xxxx:distribution/xxxx"
}
}
}
]
}
AWSハンズオンではOAIの解説だった
S3ハンズオン、Terraformで完全再現は達成
次回 lambda web adapter
Frontend Mentor
Imageがなぜか表示されない
<Image
src={`${basePath}/image-avatar.webp`}
width={64}
height={64}
alt="image-avatar"
className="m-3"
/>
svgは表示できるし、imgタグで同じsrcを指定しても動く
400 Bad Request
Unable to optimize image and unable to fallback to upstream image
const basePath = "/blog-preview-card-main";
const basePath = "/blog-preview-card-main/";
スラッシュがあるなしだけの違いだった
svgは/が多くても処理できるが、他の画像形式はスラッシュが多いと処理できないらしい
多くのOSではディレクトリに/が重なっていたとしても一つとして処理するがNext.jsはその機能を持ってない模様
Next.js
server component
Next.jsでは、static rendering と dynamic rendering を混在させることが出来る
ページをすべて static rendering にするためには、動的な関数が存在せず、キャッシュされている必要がある
dynamic functions とは?
cookie とか searchParams とか
動的か、静的か、これを考える必要はあまりない
代わりに、いつキャッシュし、いつrevalidateするのか、
そしてsteream partを分けることを考える必要がある
streaming は、loading.tsx または Suspenceとともに使われる概念
次回 client componentから
MDN CSS
スクロール時の背景画像の固定
{
background-attachment: scroll その領域に対して固定
background-attachment: fixed ウィンドウに対して固定
background-attachment: local その領域の特定の場所に固定
}
わかりやすい挙動のちがい
次回 テキスト方向の操作
4/11
type-challenge/leetcode
window関数、サブクエリなどを組み合わせる難問
sum(amount) over(
order by
visited_on range between interval 6 day preceding
and current row
) amount
上は下記と同じ
sum(amount) over(
order by
visited_on range interval 6 day preceding
) amount
上から7番目のoffsetととろうとしたとき、
where
visited_on >= (
select
visited_on
from
Customer
order by
visited_on
limit
1
) + 6
下記の書き方でも行ける
WHERE visited_on >= (
SELECT DATE_ADD(MIN(visited_on), INTERVAL 6 DAY)
FROM customer
)
lengthをプロパティとして持つtypeをgenericsとして指定しなければならない
個人開発
組み込みユーティリティ型
Terraform / AWS
ssl_support_method = "sni-only"
これの設定値の意味について
sniとは?
server name indication
要するに、一つのグローバルIPで複数の独自ドメイン、証明書を使ってアクセスが出来る仕組み?
Frontend Mentor
header, footer, main, nav, article, aside, section について
Next.js
server rendering の利点
キャッシュ可能、リクエスト間での使い回しも可能
パワーの足りない端末でも快適に利用可能
データベースに近いところで取得ができたりする
セキュア
SEO対策, social card
streaming
server components のレンダリングの2step
サーバー側
RSCpayload形式でレンダリング
client component のjavascript instructions を使ってHTMLをサーバーでレンダリングする
クライアント側
最初のロードで既にレンダリングされたHTMLが表示される
RSCとかがなんやかんや調整される
javascript instructions をhydrateしてinteractiveな画面を作る
次回、static rendering より
MDN CSS
.box {
background-position: top 20px;
background-position: top 10%;
background-position: top center;
background-position: 水平方向 垂直方向
background-position: top 20px right 10px
}
backgroundイメージが複数指定されている場合は、対応する位置にある指示に従う
.box {
background-image: url(star.png), url(big-star.png);
background-repeat: no-repeat, repeat-x
}
css gradient でグラデーションを生成できる
次回以下から
4/10
AOJ
nodeが不定数の子を持つデータ構造
テストも通る
個人開発
next.js のソースコード書き換え
色んなパターンのlaunch.jsonを工夫するも、unbound breakpoint になってしまい、
これを解消する方法が見つからず2h掛けたもののデバッグは不可能と判断
pages router でdebugができるかどうか
Terraform / AWS
こちらの方法が一番正しかった
for_each, for の使い方について
for_each はmap からresource大量作成する時に使う
terraform で ACMを作成する際にバージニア北部で作成したい
providerをus-east-1 で作ってaliasを作る
参考
Frontend Mentor
items-center
align-items: center
の意味について
主軸と交差軸が存在しalign-itemsは交差軸に対して要素を中央に揃える
flexでは交差軸は縦になる
flex-col では交差軸は横方向になるため、要素を中央揃え出来る
Next.js
void演算子の使い方がよくわからない
preload テクニック
import { getItem } from '@/utils/get-item'
// preload 関数を定義しておいて、下記のItemで呼び出す getItemを呼べるようにしておく
export const preload = (id: string) => {
// void evaluates the given expression and returns undefined
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void
void getItem(id)
}
export default async function Item({ id }: { id: string }) {
const result = await getItem(id)
// ...
}
import Item, { preload, checkIsAvailable } from '@/components/Item'
export default async function Page({
params: { id },
}: {
params: { id: string }
}) {
// starting loading item data
// Item コンポーネントを下で使うので、予め読み込み用の関数を呼び出しておく
preload(id)
// perform another asynchronous task
const isAvailable = await checkIsAvailable()
return isAvailable ? <Item id={id} /> : null
}
共同開発で使えそう
client コンポーネントに値をワタシたくない場合、明示的に指定する
MDN CSS
box model skill テスト
background-repeat プロパティで画像の繰り返し方向を指定したり出来る
no-repeatで一つにすることも
次回以下から
background-size プロパティによって contain, coverなど色々指定可能4/9
AOJ type-challenge
type First<T extends any[]> = T extends [] ? never : T[0]
extends で、型の条件分岐が可能
一番わかりやすい記事
generic constraints の具体的な使い方まで載ってる
never を網羅性チェックに使う
ラムダ式でのキャプチャ機能
これを使うことで、クロージャみたいな動作を実現できるlambda の[]内でどの変数をキャプチャするか決められる
std::function を使って簡単にラムダの型を宣言できる
void rec(int u, int p, vector<int>& d, const vector<Node>& tree) {
function<void(int, int)> f = [&](int u, int p) {
d[u] = p;
if (tree[u].right != NIL) f(tree[u].right, p);
if (tree[u].left != NIL) f(tree[u].left, p + 1);
};
f(u, p);
}
個人開発
aws のbatchGetCommandを利用して複数の検索結果を取得
検索queryの中にも重複があるとエラーになる
node の --inspect オプションについて
Next.jsにPRが提案されていて2ヶ月が経っている。
workaround な解決策が以下
Terraform / AWS
DNSの各レコードの意味
Aレコード
address
ドメインをIPアドレスに置き換えるレコード
CNAMEレコード
canonical name
canonical = 正当な
ドメインを別のドメインに転送したいときにつかう
www.hoge.jp ==> hoge.jp
aws_s3_bucket ではなく、 aws_s3_bucket_website_configuration のリソースのattributeを使う
zone_id は aws_s3_bucket のhosted_zone_idでおk
terraform でdomain validationをする方法
Frontend Mentor
先人を参考に
Next.js
preload 例が少なすぎて何をしているのか全くわからない
次回 以下から
MDN CSS
task1やっていて早速困った
参考に見たが、ベタ書きの値を入れているだけで本当に良いのか?
その他
fqdn ホスト とは
fully qualified domain name
外部入力の結果をパスとして解釈して処理する
../../../../../ect/passwd などを解釈させてパスワードを盗み取る
html 実体参照
4/8
その他
世界中のフリーランス案件を探す
how to become a freelance developper
4/7
type-challenge/leetcode
MyReadonlyの実装
constは変数について、readonly はinterface, typeのプロパティに対して使う
as const をオブジェクトの最後につけると全てのプロパティをreadonlyにできる
型定義の際、T[number]
のような使い方ができる
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
{ name: "Eve", age: 38 },
];
type Person = typeof MyArray[number];
type Person = {
name: string;
age: number;
}
ビルトインの PropertyKey なるものが存在する
// string | number | symbol
type Example = PropertyKey;
個人開発
たった10件の曲について、jsonを作成するだけでなんと500kb
20000曲のjsonサイズは 500 * 20,000 = 10,000,000
10GBになるので、ざっくり想定費用は1000円
pricing calculator
この方法だとデータベースのアイテムの変更とかが難しそうなので、例えばクエリされた回数を記録したり、とかが難しくなる
キャッシュをずっと固定で使う、クエリ回数はDynamoDBで保管する、などやり方を工夫すれば節約できるかも
とりあえずDynamoDBでアニメ100件のデータを入力してみて、料金がどれくらいかかるか
Terraform / AWS
route 53でのドメイン取得
anitunes.click で作成
Aレコードを作成し、エイリアスをs3バケットに指定する
cloudfrontでACM証明書を使用するには、バージニア北部の証明書でないと駄目らしい!
Aレコード、CNAMEレコードを作成する
証明書の作成
Frontend Mentor
READMEの整備と提出
その他Tailwindcssで作られたプロジェクトの検索
Next.js
server component でこのようにheadersでHostを削除したりすると、 bad requestになる
やはり自動でヘッダーの値の正当性をチェックしている模様
headers().delete('Host')
data fetch系は出来る限りサーバー側で行うべき
クライアントのUX体験の向上
センシティブなデータが晒されないように
await でブロックされているコンポーネントがある場合、Suspenc かloading.js
がない限りレンダリングがブロックされる。
次回 preloading から
MDN CSS
ボックスモデルについて
次回 以下から
その他
メールとセキュリティ
MTA
MUA
SMTP MUAからMTAへのメール転送 or MTA間
POP3 MTAからMUAへのメール転送
メールの過半数は迷惑メール
dv証明書
domain validation
OV証明書、EV証明書
4/6
AOJ
木の学習
次数
深さ
高さ
節点node
辺edge
子
兄弟
葉または外部節点
内部節点
根
順序木
二分木
個人開発
import { writeFile } from "fs/promises";
...
const jsonData = JSON.stringify(themes.slice(0, 15));
await writeFile("public/themes.json", jsonData, "utf-8")
publicディレクトリにjsonをアウトプットできる
Object.values, Object.entries を使うことでobjectを配列に変換
Terraform / AWS
ordered_cache_behavior
特定のpath pattern, method でのキャッシュの動作を指定できる
コンソールのどこで設定できるかは謎
amazon certificate manager
証明書のプロビジョニング
resource "aws_cloudfront_distribution" "s3_distribution" {
origin {
domain_name = aws_s3_bucket.anitunes_click.bucket_regional_domain_name
origin_id = local.s3_origin_id
}
enabled = true
# is_ipv6_enabled = true
# default_root_object = "index.html"
# logging_config {
# include_cookies = false
# bucket = "mylogs.s3.amazonaws.com"
# prefix = "myprefix"
# }
# aliases = ["mysite.example.com", "yoursite.example.com"]
default_cache_behavior {
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
target_origin_id = local.s3_origin_id
cache_policy_id = data.aws_cloudfront_cache_policy.caching_optimized.id
viewer_protocol_policy = "allow-all"
}
# price_class = "PriceClass_200"
restrictions {
geo_restriction {
restriction_type = "whitelist"
locations = ["JP"]
}
}
viewer_certificate {
cloudfront_default_certificate = true
}
}
originでs3のバケット、ドメインネームなどを指定
default_cache_behavior でキャッシュするメソッドの設定
restrictions でキャッシュが利用できる国の設定が出来る
restrictions {
geo_restriction {
restriction_type = "blacklist"
locations = []
}
}
このようにして全部の国を許可できると考えたが設定できなかった
default_root_object はoptionalだが、これを設定しないとAccess Deniedになる
今回はs3で一つのサイトしか公開していないが、複数のrouteがあるときもキャッシュは使えるのか?
また、これはcloudfront経由でアクセスしないといけないので、S3に直接アクセスした場合は使えない
URLが変わるのでこれをcloudfront強制にしたい
S3のprincipalもcloudfrontのみで良さそう
Frontend Mentor
任意の疑似クラスみたいなものも使える
カスタムプロパティの宣言
hsl値をarbitrary valueとして使える
text-[color:hsl(0,90%,90%)]
のような具合
Next.js
fontの導入
layoutの作成- Family: Josefin Sans
- Weights: 300, 400, 600
上記のfont指定をNext.jsで形にしてみる
import { ReactNode } from "react"
import { Josefin_Sans } from "next/font/google"
const josefin_sans = Josefin_Sans({
weight: ['300', '400', '600'],
subsets: ['latin'],
})
export default function Layout({ children }: { children: ReactNode }) {
return (
<div className={`${josefin_sans.className}`}>
{children}
</div>
)
}
Layoutを使って、全体に確実に適用できるようにしたい場合
pageからfontの情報を排除できていい感じ
フォントの使い方について、応用例まで含めて詳しく
import { Raleway } from "@next/font/google";
const raleway = Raleway({
variable: "--display-font",
});
MDN CSS
.container > *:first-child {
font-size: 150%;
}
.container > *:first-child::first-line {
color: red;
}
子要素である全ての任意のセレクタ(*)を対象にし、直接の子要素に限定(>)、
その中でも最初の子要素にのみセレクタが適用されるようになる
task 3, 4
次回 task5と以下から
その他
4/5
type-challenge/leetcode
sum(if(...)) で大体解ける
extendsについて
型を渡す側に対して制約を掛ける
interface T {
name: string
age: number
}
type hoge = keyof T
// hoge = "name" | "age"
type name = 'firstname' | 'lastname'
type TName = {
[key in name]: string
}
// TName = { firstname: string, lastname: string }
個人開発
external data sourceを使って、外部コマンドの実行結果をterraformで利用できる
.env の他に .env.local, .env.developmentが使える模様
terraform destroy -target を使うと一部のリソース削除ができるが、推奨されていない
Terraform / AWS
cloudfront
キャッシュサーバーのサービス。エッジで展開する
キャッシュの有効期限はアプリケーションサイドで決める?
route53
マネージドDNSサービス。フェイルオーバールーティングポリシー
(ヘルスチェックがNGになったらS3の別のサイトを表示する)もある。
acm
証明書の提供。Cloudfrontやapi gateway を使う場合は無料で使えるらしい。
cloudfront distributionの設定
大体はドメインネームのエイリアスというようなことがなんとなくわかった
AWS-managed なポリシーをhuman readableな文で引用する方法
次回
引き続きcloudfrontをterraformで設定していく
Frontend Mentor
(Error: ' can be escaped with ', ‘, ', ’. react/no-unescaped-entities)
'シングルクォートが入った文字列を``で囲む
:root で書くことで使える模様
tailwind でcss var を使う
次回 色味やグラデーションをREADMEの指定に合わせる
READMEを整備する
`` で囲む以外のやり方を試す
frontend mentorでsubmitする
Next.js
おそらく、関数の中で関数定義したときに、caller つまり呼び出し元からはアクセスできない変数のこと
A new private key is generated for each action every time a Next.js application is built. This means actions can only be invoked for a specific build.
これの意味がわからない。
サーバーアクションは特定のビルド時しか呼べない?
Next.jsは関数の内部を暗号化するようで、そのビルドの際に毎回違うprivate keyが作成され、それがサーバー側で復号に用いられている?
だから複数の環境でNext.jsを相補的に動かすような場合、復号キーが違って不都合が生じる場合がある
それを防ぐために、
process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
これで環境変数を上書きし、復号キーを統一することが出来る模様
next.js はPOSTリクエストでしかserver action を invokeできない
また、host と origin ヘッダーの一致を確かめるため、これらが違うとリクエストは中止される
次回ここから
use serverを使っているpageでheaderを書き換えたら動かなくなるのか検証
MDN CSS
task 1の回答
h1 {
color: blue;
}
h2 {
color: white;
background: blue;
}
span {
font-size: 200%
}
task2 の回答
#special { background: yellow; }
.alert { border: 1px solid grey; }
.alert.stop { background: red; }
.alert.go { background: green; }
task3 意外とわからん
nth-childを使う模様
a[href]:visited { color: green }
a[href] { color: orange }
a[href]:hover { text-decoration: none }
.container::first-line { color: red }
.container > p:first-child { font-size: 150% }
ここに回答例が載っているので困ったら見る
次回 task3 から task5 まで
4/4
AOJ
int solve(int len, const vector<int>& nums, int min_all) {
int ans = 0;
vector<int> dest(nums.begin(), nums.end());
vector<int> T(len + 1, -1);
vector<bool> V(len, false);
// まず、ソート後の目標とする配列を用意する
sort(dest.begin(), dest.begin() + len);
rep(i, len) { T[dest[i]] = i; }
rep(i, len) {
if (V[i]) continue;
int cur = i;
int sum = 0;
int min_in_cycle = VMAX;
int cycle_len = 0;
while (true) {
V[cur] = true;
++cycle_len;
const int v = nums[cur];
min_in_cycle = min(min_in_cycle, v);
sum += v;
cur = T[v];
if (V[cur]) break;
}
// サイクル内の要素での最小コスト vs サイクル外の最小値を借りた場合のコスト
ans += min(sum + (cycle_len - 2) * min_in_cycle,
sum + min_in_cycle + (cycle_len + 1) * min_all);
}
return ans;
}
何を表しているかわからなかったV, Tの意味がようやくわかった
計数ソートの考えが一部で取り入れられていて、
Tは、要素として、与えられた数字列の各数字がソート後の配列で配置されるべきインデックスを示している。
要するに idx が 各数字、その要素の数字が配置されるべきインデックスになっている。
vはサイクル内の数字を表していて、curはその数字がソート後に配置されるべきインデックスを示している
keyを各数字とし、要素を配置されるべきインデックスとして収納されている辞書であればわかりやすかった。
計数ソートもそうだが、実際は辞書やmapの方が無駄なインデックスがなくて済むのでは?
Vの要素はそのインデックスの要素(numsに対応する)が探索済みかどうか、を示す
サイクルの長さが1つの場合はV[cur]がtrueになるので、次のサイクルに移ることとなる
サイクルの長さが2以上の場合は、サイクルの最後でサイクルの最初の要素に戻ってくることになるので、v[cur]がtrueとなりループ終了
書籍に掲載されている変数名がゴミなので、より人間が読める形での変数名に変換した
個人開発
あとからフィルタリングできる程度
assume roleとは何なのか?
keybaseを使わず、自前でgpg鍵を用意してパスワードを複合したりする
outputされたアクセスキーをどうやって複合するかという肝心の手順がない
keybaseの紹介 記事古い
keybaseやら鍵を使わず、stateファイルに平文でキーが保存される例
iamポリシーの付与は以下のページに詳細が載っている
keybaseコマンドでdecryptする例が載っている
keybaseのインストール方法
gpg鍵について
Terraform / AWS
AWSのポリシーでよく見る principal とは?
誰にリソースのアクセスを許可するか、という話
awsのユーザーARNを使うこともできる
SID とは?
説明的なid名をつければよさそう。
メタデータが
application/octet-stream
になってしまう
とはいえ、for_eachを使っている都合上、content-typeは各々違って当然なので、指定が難しい
この問題に対する回答
Terraformで使える関数を把握する
アクセスするURLが間違っていた模様
objectの方からURLを取得すると上手く行かない
以下のコードでとりあえず今あるファイルの種類に応じたcontent-typeの設定が可能
locals {
content_types = {
"js" = "application/javascript"
"html" = "text/html"
"css" = "text/css"
"png" = "image/png"
"ico" = "image/x-icon"
}
}
resource "aws_s3_object" "resources" {
bucket = aws_s3_bucket.anitunes_click.id
for_each = fileset("./resources/", "**")
key = each.value
source = "resources/${each.value}"
content_type = lookup(local.content_types, reverse(split(".", each.value))[0], "text/plain")
etag = filemd5("resources/${each.value}")
}
Frontend Mentor
常にcompleteなclass name を使わないとエラーになる
その関係上、 arbitrary value で対応するには bg-[url(/base-apparel-coming-soon-master/bg-pattern-desktop.svg)]
これをベタ書きせねらばならず、実用的でない。
総合的に見れば、変数によって文字列の再利用が可能な以下がよさそう
<div
className="md:hidden bg-cover w-full h-80 mb-10"
style={{
backgroundImage: `url(${basePath}/hero-mobile.jpg)`,
}}
></div>
tailwindのクラス名並べ替えを自動で
上のpluginは古いため動かなかった下の最新の、公式のプラグインを使うことで動いた
Next.js
useOptimistic
Next.jsの公式ドキュメントでは何を言っているかわからない
Reactの公式
multiple form actionについて
requestSubmit
最も近い祖先のformをtriggerする
サーバーアクションが完了するまでに暫定的なUIを表示したい
useOptimistic や useTransition を使いたい
次回セキュリティから
開発者は、server actionがpublicに公開されているAPIを扱うかのごとく開発しなければならない
認証忘れずに
MDN CSS
次回以下より
その他
4/3
leetcode
個人開発
ローカルで動くプログラムへの認証方法
まずiamユーザーをコンソールログイン機能なしで作成し、
セキュリティ認証情報からアクセスキーを作成
下記の認証方法を頼りに、.envに環境変数を設定する
AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY の設定だけでおkまだエラーが出たので下記を見るがユーザーに割り当てられたポリシー的には全く問題なさそう
アプリ再起動で治った。
iamロールの作成もTerraformで行い、アクセスキーをoutputでローカルにのみ保存するようにすれば
destroyでまとめて削除できそうなので、次回やってみたい
.env以外の .aws.env みたいなファイルを自動で作って更新できるようにできないか?
とりあえず認証が通ってクエリを通すところまでは達成
assume a role が代替として使えるかと思ったが、よくわからないのでスキップ
Terraform / AWS
text/html image/png audio/mpeg など
etagを設定しないと、index.html をupdateしても検知してくれない
ファイルを上げる際にオブジェクトごとにいちいちresourceを書くのがめんどくさい↓
for_each を使ってまとめて作成できそう
次回ディレクトリごとアップロード
Frontend Mentor, Next.js
redirect関数はreturnのように関数の戻り値に影響を与える模様
どのように関数の戻り値を推論して決定するのか?が謎
zod, useFormStateを利用してサーバーサイドのバリデーションを実装
次回 frontend mentor
bgイメージをarbitary valuesで対応
MDN CSS
疑似クラスで、特定の状態にあるときにクラスを追加したかのように振る舞う
疑似要素で、あたかもDOMに要素を追加したかのように動作する
::before で特定のセレクタの前に何か content を使って要素の追加が可能
.box p
.box クラスを持つ要素の子孫全てに適用される
子結合子
.box > p
.box クラスを持つ要素の子にのみ適用される
次回、次兄弟結合子から
その他
以下のようにシェルスクリプトでディレクトリごとに走査したい場合に使える
for dir in */; do
ECSからサーバーレスに移行した記事
4/2
AOJ
0 1 2 3 4 5 6 7 8 9 10 (idx)
1 2 7 8 9 10 (nums)
0 0 1 0 0 0 0 2 3 4 5
V
0 0 0 0 0 0
1 0 0 0 0 0
サイクルを求める計算のやり方イマイチわからない。。。
なぜそうなる?のか
個人開発
dynamodbテーブルをterraformで作成
docker環境にしたせいで、AWS CLIが使えない
docker内からでも安全にAWSを操作したい
Terraform / AWS
aws_s3_bucket_public_access_block
でデフォルトでpublic access blockを解除できる
これでpublic access blockを解除して即公開可能ではなく、bucket policyを定義して初めて公開できる
static_website_hosting のような設定項目はなく、
以下のリソースを定義するだけでstaticウェブサイトの定義が可能
aws_s3_bucket_website_configuration
バケットポリシーの作成
次回
ファイルのアップロード
こちら参考にできそう
Frontend Mentor
useFormStateを参考に、stateを使わずにformの送信ができる動作の実現を目指しているが下記のエラー
Overload 1 of 2, '(action: (state: { errors: { email?: string[] | undefined; }; } | undefined) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined, initialState: { ...; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.
Argument of type '(prevState: any, formData: FormData) => Promise<{ errors: { email?: string[] | undefined; }; } | undefined>' is not assignable to parameter of type '(state: { errors: { email?: string[] | undefined; }; } | undefined) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined'.
Target signature provides too few arguments. Expected 2 or more, but got 1.
Overload 2 of 2, '(action: (state: { errors: { email?: string[] | undefined; }; } | undefined, payload: FormData) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined, initialState: { ...; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.
Object literal may only specify known properties, and 'message' does not exist in type '{ errors: { email?: string[] | undefined; }; }'
長すぎて読めない。
これが
(prevState: any, formData: FormData) => Promise<
{ errors: { email?: string[] | undefined; }; } | undefined
>
これにnot assignable ということらしい
(state: { errors: { email?: string[] | undefined; }; } | undefined) => {
errors: { email?: string[] | undefined; };
} | Promise<
{ errors: { email?: string[] | undefined; }; } | undefined
> | undefined
learn next.js を見直して再実装する必要がありそう
Next.js
FrontEnd mentor の続き
input, select タグのなかに name="hoge" のような属性を埋め込むと、
formDataから取得が可能になる
MDN CSS
属性セレクター
属性の値によってセレクタを適用するか決められる
a[href^="hoge"]
のように正規表現っぽい指定方法もある
a {
border: 5px solid grey;
}
a[title] {
border-color: pink
}
a[href*="contact"] {
border-color: orange
}
a[href^="https"] {
border-color: green
}
<ul>
<li><a href="https://example.com">Link 1</a></li>
<li><a href="http://example.com" title="Visit example.com">Link 2</a></li>
<li><a href="/contact">Link 3</a></li>
<li><a href="../contact/index.html">Link 4</a></li>
</ul>
次回、疑似クラス、疑似要素の組み合わせから
動的疑似クラス→ホバーした時に適用されるCSSの決定など
first-line、first-child などで最初の要素のみを指定したり、
最初の行がまるでspanでラップされているかのように振る舞う
4/1
AOJ
コストを計算して小さい方を採用する
// numsは同じ型のvector 下記のような感じでコピーできる
const vector<int> dest(nums);
// sort
sort(dest.begin(), dest.end());
個人開発
spotify APIの検索精度調査
英語での検索だとあまり正確な結果が出てこない場合がある
spotify api クエリについて
Terraform / AWS
route53でAWSクレジットを利用したドメインの取得ができそう
billing and cost management/クレジット からクレジットが適用可能な製品を確認
ホストゾーン数 というのがよくわからない。
これは固定費として必ずかかるものなのか、従量課金なのか?
無料枠は存在するのか?
お名前ドットコムなどで普通に取得しても良いかも知れない。
クレジットが使えるうちに固定費の支払いをすることで料金請求になれておくべきかも。
Frontend Mentor
order-2 などの指定をすることで、flexなどを利用したときDOMでの登場順とは違う順番に要素を並べることが出来る
Next.js
useFormStatus と useFormState が存在する
useFormStatus はフォーム送信時のpending状態を取得できる
useFormState を使うことで リデューサのような動作になる
サーバーバリデーション後にクライアントにメッセージを表示できる
actionに、formDataに加えてprevState引数が一個増える
次回以下 optimistic updates から
MDN CSS
カンマ区切りによって、複数のセレクタに対してまとめて設定を行える
単なるスペース区切りだと、 h1 div とかだと h1 の直後に来たdiv要素、となる
特定の要素の特定のプロパティ、値を持つセレクタも存在する
a[href="https://example.com"] {
...
}
タイプセレクタ
要素名をそのまま書くやつ。
ユニバーサルセレクタ
- で全選択するやつ。
ブラウザの動作リセットか、可読性の向上でのみ使うべき。
次回 以下から