SMV’s diary (original) (raw)
この広告は、90日以上更新していないブログに表示しています。
Amplify ドキュメント
https://docs.amplify.aws/start/q/integration/next/
■15. 投稿ページの下準備
uuidというのを利用するので、インストール
yarn add uuid
pages/create-post.jsを作成。
まずは、第一段階目のコーディング。
import { withAuthenticator } from "@aws-amplify/ui-react"; import { useState, useRef, React } from "react"; import { API } from "aws-amplify"; import { useRouter } from "next/router"; import { v4 as uuid } from "uuid";
const initialState = {title: "", content: ""}
function CreatePost(){ const [post, setPost] = useState(initialState) const { title, content } = post const router = useRouter
function onChange(e){ setPost(() => ({ ...post, [e.target.name]: e.target.value })) }
async function createNewPost(){ if(!title || !content) return; const id = uuid(); } }
export default CreatePost;
ここからAPIを利用して、GraphQLのMutationでCreatePostができるようにしていく。
import { withAuthenticator } from "@aws-amplify/ui-react"; import { useState, useRef, React } from "react"; import { API } from "aws-amplify"; import { useRouter } from "next/router"; import { v4 as uuid } from "uuid"; import { createPost } from "../src/graphql/mutations"
const initialState = {title: "", content: ""}
function CreatePost(){ const [post, setPost] = useState(initialState) const { title, content } = post const router = useRouter
function onChange(e){ setPost(() => ({ ...post, [e.target.name]: e.target.value })) }
async function createNewPost(){ if(!title || !content) return; const id = uuid(); post.id = id
await API.graphql({
query: createPost,
variables: {input: post},
authMode: "AMAZON_COGNITO_USER_POOLS"
})
// router.push(/posst/${id}
)
}
return(
Create new Post
ここまではまだ準備段階。
router.pushもコメントアウトしておく。
まだh1が表示されるだけである。
■16. 投稿ページのフォーム作成
15の続き。
wigetフォームを簡単に作成できるモジュールをインストール。
SimpleMDEはコードも書ける!
npm install react-simplemde-editor react-markdown
create-post.jsへインポートする。
(中略) import SimpleMDE from "react-simplemde-editor" import "easymde/dist/easymde.min.css"
タイトルの入力欄と、ウィジェットフォームを表示させるようにする。
(中略) return(
Create new Post
<SimpleMDE value={post.content} onChange={(value) => setPost({...post, content: value})} />投稿できるようするために、ウィジェットの下に「投稿を作成する」ボタンを追加する。
Create Post
非同期で実行されるcreateNewPost関数は、titleまたはcontentがfalsyの場合、何も中身のないものがreturnされる。
中身があれば、uuidで、世界で一つだけのidを取得し、postのidに設定される。
そして、待っていた API,graphqlが稼働する。
実行されるクエリはcreatePost、 variableはinputで投稿(post)されたもの。投稿にはコンテンツタイトルを付ける必要がある。
そして、これにより、authModeがAmazonのコグニートのユーザープールにあるものとして認識されるようになる。
したがって、ログインした人だけが、投稿を作成する権限がある。
しかし、このままでは駄目。
CreatePostコンポーネントは、 withAuthenticator でラップしなければ、機能しない。
export default withAuthenticator(CreatePost);
しかし、これでも、まだ駄目。
更新すると、参照エラーで「ナビゲーターが定義されていない」と出る。
これは、SSR、つまりサーバー側のレンダリングと関係がある。
それは
import SimpleMDE from "react-simplemde-editor"
に原因がある。
そのため、サーバー側のレンダリングをするためには、少し手を加える必要がある。
ここで登場するのがdynamicインポート。
「JavaScriptモジュールを動的にインポートして操作できます。また、SSRでも機能します。」
とのこと。
import dynamic from "next/dynamic"; const SimpleMDE = dynamic(() => import("react-simplemde-editor"), {ssr: false})
この文法通り、SSRのtoggleを渡す必要がある。
ここまでの全体感。
import { withAuthenticator } from "@aws-amplify/ui-react"; import { useState, useRef, React } from "react"; import { API } from "aws-amplify"; import { useRouter } from "next/router"; import { v4 as uuid } from "uuid"; import { createPost } from "../src/graphql/mutations" import dynamic from "next/dynamic"; const SimpleMDE = dynamic(() => import("react-simplemde-editor"), {ssr: false}) // import SimpleMDE from "react-simplemde-editor" import "easymde/dist/easymde.min.css" const initialState = {title: "", content: ""} function CreatePost(){ const [post, setPost] = useState(initialState) const { title, content } = post const router = useRouter function onChange(e){ setPost(() => ({ ...post, [e.target.name]: e.target.value })) } async function createNewPost(){ if(!title || !content) return; const id = uuid(); post.id = id
await API.graphql({
query: createPost,
variables: {input: post},
authMode: "AMAZON_COGNITO_USER_POOLS"
})
// router.push(/post/${id}
)
}
return(
Create new Post
<SimpleMDE value={post.content} onChange={(value) => setPost({...post, content: value})} /> Create Post■17. 動的IDと新しく作成された投稿の表示
まずは、pagesディレクトリに新しく posts/[id].js を新規作成。
ここでの考え方は、作成投稿に戻って、先に進むということです。
import { API } from 'aws-amplify' import { useRouter } from 'next/router' import ReactMarkDown from 'react-markdown' import '../../configureAmplify' import { listPosts, getPost } from '../../src/graphql/queries' export default function Post({post}){ const router = useRouter() if(router.isFallback){ return
{post.title}
これで、create-post.jsでコメントアウトしていた、router.pushを解除することができる。
import { withAuthenticator } from "@aws-amplify/ui-react"; import { useState, useRef, React } from "react"; import { API } from "aws-amplify"; import { useRouter } from "next/router"; import { v4 as uuid } from "uuid"; import { createPost } from "../src/graphql/mutations" import dynamic from "next/dynamic";
const SimpleMDE = dynamic(() => import("react-simplemde-editor"), {ssr: false}) // import SimpleMDE from "react-simplemde-editor" import "easymde/dist/easymde.min.css" const initialState = {title: "", content: ""} function CreatePost(){ const [post, setPost] = useState(initialState) const { title, content } = post const router = useRouter function onChange(e){ setPost(() => ({ ...post, [e.target.name]: e.target.value })) } async function createNewPost(){ if(!title || !content) return; const id = uuid(); post.id = id
await API.graphql({
query: createPost,
variables: {input: post},
authMode: "AMAZON_COGNITO_USER_POOLS"
})
router.push(/post/${id}
)
}
return(
Create new Post
<SimpleMDE value={post.content} onChange={(value) => setPost({...post, content: value})} /> Create Postしかし、このままでは、ルーターは認識するが、投稿を表示することはできない。
何か足りないか?
「Decrypt」、投稿自体を復号化し、自分自身をレンダリングする、という方法がある。
それは、getStaticPathsを使うことになる。
これによって、表示したい場所へのパスが得られる。
[id].js
import { API } from 'aws-amplify' import { useRouter } from 'next/router' import ReactMarkDown from 'react-markdown' import '../../configureAmplify' import { listPosts, getPost } from '../../src/graphql/queries' export default function Post({post}){ const router = useRouter() if(router.isFallback){ return
{post.title}
export async function getStaticPaths(){ const postData = await API.graphql({ query: listPosts }) const paths = postData.data.listPosts.items.map(post => { params: { id:post.id } }) return{ paths, falback: true } }
次に、投稿データを渡すことができるようにする別の関数を作成する必要がある。
getStaticPropsを使う。
全体感としては、以下になる。
import { API } from 'aws-amplify' import { useRouter } from 'next/router' import ReactMarkDown from 'react-markdown' import '../../configureAmplify' import { listPosts, getPost } from '../../src/graphql/queries' export default function Post({post}){ const router = useRouter() if(router.isFallback){ return
{post.title}
■18. インデックスルートにマークアップとスタイリングを追加する
まずは、getStaticPropsにプロパティをもう一つ追加する。
export async function getStaticProps({params}){ const { id } = params const postData = await API.graphql({ query: getPost, variables: {id}, }) return { props :{ post: postData.data.getPost }, revalidate: 1 } }
これで、[id].jsの全体感としては、以上になる。
import { API } from 'aws-amplify'
import { useRouter } from 'next/router'
import ReactMarkDown from 'react-markdown'
import '../../configureAmplify'
import { listPosts, getPost } from '../../src/graphql/queries'
export default function Post({post}){
const router = useRouter()
if(router.isFallback){
return
}
return(
{post.title}
By {post.username}
{post.content}
)
}
export async function getStaticPaths(){
const postData = await API.graphql({
query: listPosts
})
const paths = postData.data.listPosts.items.map((post) => ({
params: { id:post.id }
}))
return{
paths,
fallback: true
}
}
export async function getStaticProps({params}){
const { id } = params
const postData = await API.graphql({
query: getPost,
variables: {id},
})
return {
props :{
post: postData.data.getPost
},
revalidate: 1
}
}
index.jsのスタイリングなどの微調整
import { useState, useEffect } from "react" import { API } from 'aws-amplify' import { listPosts } from "../src/graphql/queries" import Link from "next/link" export default function Home() { const [posts, setPosts] = useState([]) useEffect(() => { fetchPosts() }, []) async function fetchPosts(){ const postData = await API.graphql({ query: listPosts }) setPosts(postData.data.listPosts.items) } return (
My Post
{ posts.map((post, index) => ( <Link key={index} href={/post/${post.id}
}>
{post.title}
Author: {post.username}
) }
■18. マイ投稿ページの作成
Amplify ドキュメント
https://docs.amplify.aws/start/q/integration/next/
■0. AWSのセットアップ
アカウントだけは先に作っておくこと。それ以外は何もしなくても大丈夫。I AMユーザーの管理者権限も一応念のために先にあると良いが、このプロジェクトのセットアップには必要ない。
■1. Amplify CLIのインストール
ローカル端末にAmplify CLIのインストール
【mac】sudo npm install -g @aws-amplify/cli 【windows → 管理者権限でpower shellを開く】npm install -g @aws-amplify/cli
※いきなりこちらを実行でOK。
Amplify CLI の初期セットアップ
Amplify を使ったプロジェクト用のI AMユーザを、以下のコマンドで生成する。
amplify configure
プロファイル名を設定しておくと、initするときに、明確に紐付けできる。
(余談)既存カテゴリの更新、削除を行うことも可能
(更新)
amplify update (カテゴリ名)
(削除)
amplify remove (カテゴリ名)
(設定のステータスの確認)
amplify status (カテゴリ名)
再度ステータスを確認
amplify status api
→"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add " will allow you to add features like user login or a backend API
(Try "amplify add api" to create a backend API and then "amplify push" to deploy everything)
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud
■2. AWS AppSyncでコンソール画面をチェック
ログインした状態でaws内で、
AWS AppSync
で検索。
ここがQueryの管理画面のベースになる。
■3. 開発プロジェクトの作成
yarn install *インストールしていない場合
npm install --global yarn yarn --version
Next.jsフレームワークのインストール
npx create-next-app プロジェクト名
※npm同様、プロジェクトをコピーするときは「yarn install」でできるようだ。
○TypeScript の導入
https://nextjs.org/learn/excel/typescript/create-tsconfig
2-1. 空のtsconfig.json作成
touch tsconfig.json(macのターミナル) New-Item tsconfig.json(Windowsのシェルスクリプト)
2-2. 必要moduleのインストール
yarn add -D typescript @types/react @types/node
2-3. 開発server起動
yarn dev
そうすると、tsconfig.json に初期設定が自動的に反映される。
2-4. 「pages」ディレクトリの、_app.jsと index.jsを -> tsx へ拡張子変更
2-5. _app.jsを、AppProps型に編集
import { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } export default MyApp
※yarn add -D typescript @types/react @types/node でtypescriptをインストールしたとき、tsconfig.jsonで
(中略) "types": ["typed-query-selector"] , (中略) "moduleResolution": "node", (中略)
が欠けた状態で出力された。
windowsでのインストールは気をつけたい。
まずは
yarn add typed-query-selector
で、モジュールをインストール。
で、一度閉じて開きなおしたら、直った。
念のため、完全版は以下。
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext", ], "types": ["typed-query-selector"] , "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "incremental": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve" }, "include": [ "next-env.d.ts", "/*.ts", "/*.tsx" ], "exclude": [ "node_modules" ] }
○Tailwind CSS の導入
https://tailwindcss.com/docs/guides/nextjs
3-1. 必要moduleのインストール
yarn add tailwindcss@latest postcss@latest autoprefixer@latest
3-2. tailwind.config.js, postcss.config.jsの生成
npx tailwindcss init -p
3-3. tailwind.config.jsのpurge設定編集
tailwind.cssの適用範囲を意味する。
module.exports = { content: [ "./pages//*.{js,ts,jsx,tsx}", "./components//*.{js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], }
3-4. ルートディレクトリに、componentsフォルダを作成
mkdir components
3-5. globals.cssの編集
@tailwind base; @tailwind components; @tailwind utilities;
○SASSを読み込めるようにする
yarn add sass npm install sass
cssをscssにリネーム。pages内のファイルネームも忘れずに。
yarn環境で、間違えてnpmで入れないこと。その後の操作で、コンパイルエラーになって、最初からやり直す。
○React-Bootstrapをインストール
https://react-bootstrap.github.io/getting-started/introduction
yarn add react-bootstrap bootstrap@5.1.3 npm install react-bootstrap bootstrap@5.1.3
こちらの方がよりbootstrapライクである。
○Reactのアイコンライブラリ
https://react-icons.github.io/react-icons/
yarn add react-icons npm install react-icons
○fontawesomeのReact版アイコンライブラリ
https://fontawesome.com/v5/docs/web/use-with/react
yarn add @fortawesome/fontawesome-svg-core yarn add @fortawesome/free-solid-svg-icons yarn add @fortawesome/react-fontawesome yarn add @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/fontawesome-svg-core npm install --save @fortawesome/free-solid-svg-icons npm install --save @fortawesome/react-fontawesome npm install --save @fortawesome/free-brands-svg-icons
○React Playerをインストール
https://www.npmjs.com/package/react-player
yarn add react-player npm i -D react-player
■4. Amplifyの導入
プロジェクトのルートディレクトリで初期化コマンドを実行
amplify init
質問が対話形式で出てくる。
? Enter a name for the project?
→プロジェクト名を入れる
? Initialize the project with the above configuration? (Y/n)
→Y で。(プロジェクトを初期化しますか? と聞かれている)
? Select the authentication method you want to use: (Use arrow keys)
→AWS profile で。(使用する認証方法を選択します、と聞かれている)
? Please choose the profile you want to use(Use arrow keys)(使用したいプロファイルを選択してください、と聞かれている)
→default で。
Amplify CLIをインストールした際のユーザー名を選択。
終わると
Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add " will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud
Pro tip:
Try "amplify add api" to create a backend API and then "amplify push" to deploy everything
と出てくる。amplify のデプロイ周りの基本コマンドで、よく使うことになる。
○必要な依存関係をインストール
yarn add aws-amplify @aws-amplify/ui-react@1.x.x
■5. AppSync API、GraphQLとスキーマの設計
GraphQL APIをアプリに追加(「カテゴリ」という単位でバックエンドの設定を追加することになる)
amplify add api
いろんな質問が対話形式で出てくる。