Quickstarters
CRUD Samples
How to Create a Basic CRUD App with Preact?
45 分
概要 このガイドでは、preactを使用してcrud(作成、読み取り、更新、削除)アプリケーションを開発します。 「 basic crud app preact 」という名前のback4appプロジェクトを初期化するところから、データを簡単に管理するシステムを構築する手順を説明します。このプロジェクトは、堅牢なバックエンドと、preactで構築された洗練されたミニマルなフロントエンドを提供します。 まず、back4appで新しいプロジェクトを設定し、効率的なデータベーススキーマを手動またはback4app aiアシスタントの助けを借りて作成します。この設計は、すべての基本的なcrud機能をサポートします。 次に、データ管理を簡素化するドラッグアンドドロップインターフェースであるback4app admin appを紹介します。このツールを使用して、レコードを迅速に追加、変更、または削除できます。 最後に、rest/graphqlを使用してpreactフロントエンドをback4appに接続し、バックエンドが高度なアクセスルールで安全であることを確認します。 このチュートリアルの終わりまでに、ユーザー認証と堅牢なデータ管理を備えた本番環境向けのwebアプリケーションを作成できるようになります。すべてpreactで構築され、back4appによって支えられています。 主な洞察 信頼できるバックエンドを使用してデータを効率的に管理するcrudアプリケーションの構築をマスターします。 スケーラブルなデータモデルを設計し、最適なユーザーエクスペリエンスのためにpreactフロントエンドと統合する方法を学びます。 ドラッグアンドドロップのback4app admin appが作成、読み取り、更新、削除操作をどのように簡素化するかを発見します。 アプリケーションを迅速に立ち上げるためのコンテナ化を含むデプロイメント戦略を理解します。 前提条件 始める前に、次のことを確認してください back4appアカウントと初期化されたプロジェクト。 ガイダンスについては、 https //www back4app com/docs/get started/new parse app を確認してください。 preact開発環境。 https //github com/preactjs/preact cli などのツールを使用し、node js(v14以降)がインストールされていることを確認してください。 javascript、preact、およびrest apiの基本的な知識。 必要に応じて、 https //preactjs com/guide/v10/ を参照してください。 ステップ1 – プロジェクトの設定 back4appプロジェクトの初期化 back4appアカウントにサインインします。 ダッシュボードで「新しいアプリ」オプションを選択します。 プロジェクトに名前を付けます basic crud app preact として、セットアップのプロンプトに従います。 新しいプロジェクトを作成 作成後、あなたのプロジェクトはback4appダッシュボードに表示され、バックエンド構成の基礎が築かれます。 ステップ2 – データベーススキーマの作成 データモデルの構造化 私たちのcrudアプリには、いくつかのコレクションが必要です。以下は、crud操作をサポートするために必要なコレクションとフィールドの例です。 1 アイテムコレクション このコレクションは各アイテムの詳細を保持します。 true left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type 2 ユーザーコレクション これはユーザーの資格情報とプロフィールの詳細を保持します。 true left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type left unhandled content type これらのコレクションは、back4appダッシュボードを介して手動で作成できます。各コレクションの新しいクラスを追加し、適切なフィールドを定義します。 新しいクラスを作成 データ型を選択し、列に名前を付け、デフォルト値と必須フラグを設定することで、列を追加できます。 列を作成 スキーマ作成のためのback4app aiアシスタントの使用 back4appで利用可能なaiアシスタントは、コレクションとフィールドを説明するプロンプトに基づいてスキーマを自動生成できます。この機能はセットアップを迅速化し、一貫性を確保します。 aiアシスタントの使用手順 back4appダッシュボードからaiアシスタントを開きます。 データモデルの詳細な説明を入力します。 自動生成されたコレクションとフィールド定義を確認し、それをプロジェクトに適用します。 サンプルプロンプト create these collections in my back4app project 1\) collection items \ fields \ id objectid (auto generated) \ title string \ description string \ created at date (auto generated) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) このアプローチは時間を節約し、構造化されたスキーマを保証します。 ステップ3 – 管理アプリの有効化とcrud操作の管理 管理アプリの紹介 back4app管理アプリは、バックエンドデータを簡単に管理するためのノーコードインターフェースを提供します。ドラッグアンドドロップ機能により、手間なくcrud操作を実行できます。 管理アプリの有効化 back4appダッシュボードの「その他」メニューに移動します。 「管理アプリ」を選択し、 「管理アプリを有効にする。」 最初の管理ユーザーを設定します。これにより、 b4aadminuser やシステムコレクションなどの役割も設定されます。 管理アプリを有効にする 有効化後、管理アプリにログインしてデータを管理します。 管理アプリダッシュボード 管理アプリでのcrud操作の実行 インターフェース内でできること レコードを追加する どのコレクション(例:アイテム)でも「レコードを追加」オプションを使用して新しいエントリを作成します。 レコードを表示および編集する レコードを選択してその詳細を確認したり、フィールドを修正したりします。 レコードを削除する もはや必要のないエントリを削除します。 この直感的なツールは、データ管理を効率化することでユーザー体験を向上させます。 ステップ4 – preactフロントエンドをback4appに接続する バックエンドが整ったので、preactフロントエンドを統合する時が来ました。 オプションa parse sdkを利用する parse sdkをインストールする npm install parse preactプロジェクトにparseを設定します。ファイルを作成します(例: src/parseconfig js ) // src/parseconfig js import parse from 'parse'; // insert your back4app credentials here parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; preactコンポーネントにparseを統合します。例えば、アイテムを取得して表示するコンポーネントを作成します // src/components/itemslist js import { h } from 'preact'; import { useeffect, usestate } from 'preact/hooks'; import parse from ' /parseconfig'; const itemslist = () => { const \[items, setitems] = usestate(\[]); useeffect(() => { const fetchitems = async () => { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); setitems(results); } catch (error) { console error("error fetching items ", error); } }; fetchitems(); }, \[]); return ( \<div> \<h2>items\</h2> \<ul> {items map(item => ( \<li key={item id}> {item get("title")} — {item get("description")} \</li> ))} \</ul> \</div> ); }; export default itemslist; オプションb restまたはgraphqlの活用 parse sdkが利用できない場合は、crud操作にrestまたはgraphqlを使用します。例えば、restを介してアイテムを取得するには // sample rest call to retrieve items const fetchitems = async () => { try { const response = await fetch('https //parseapi back4app com/classes/items', { headers { 'x parse application id' 'your application id', 'x parse rest api key' 'your rest api key' } }); const data = await response json(); console log('fetched items ', data results); } catch (error) { console error('error fetching items ', error); } }; fetchitems(); 必要に応じて、これらのapi呼び出しをpreactコンポーネントに統合します。 ステップ5 – バックエンドセキュリティの強化 アクセス制御リスト(acl)の使用 オブジェクトにaclを割り当てることでデータを保護します。たとえば、プライベートアイテムを作成するには async function createprivateitem(itemdata, owneruser) { const items = parse object extend('items'); const item = new items(); item set('title', itemdata title); item set('description', itemdata description); // configure acl only the owner has read/write access const acl = new parse acl(owneruser); acl setpublicreadaccess(false); acl setpublicwriteaccess(false); item setacl(acl); try { const saveditem = await item save(); console log('private item created ', saveditem); } catch (error) { console error('error saving item ', error); } } クラスレベルの権限(clp) back4appダッシュボード内で、各コレクションのclpを調整して、認証されたユーザーまたは承認されたユーザーのみにアクセスを制限します。 ステップ 6 – ユーザー認証の実装 ユーザーアカウントの設定 back4appは、認証管理のためにparseのuserクラスを利用しています。あなたのpreactアプリケーションでは、以下のようにユーザーのサインアップとログインを管理します // src/components/auth js import { h } from 'preact'; import { usestate } from 'preact/hooks'; import parse from ' /parseconfig'; export const signup = () => { const \[username, setusername] = usestate(''); const \[password, setpassword] = usestate(''); const \[email, setemail] = usestate(''); const handlesignup = async (e) => { e preventdefault(); const user = new parse user(); user set('username', username); user set('password', password); user set('email', email); try { await user signup(); alert('user registration successful!'); } catch (error) { alert('registration error ' + error message); } }; return ( \<form onsubmit={handlesignup}> \<input type="text" placeholder="username" value={username} onchange={e => setusername(e target value)} /> \<input type="password" placeholder="password" value={password} onchange={e => setpassword(e target value)} /> \<input type="email" placeholder="email" value={email} onchange={e => setemail(e target value)} /> \<button type="submit">sign up\</button> \</form> ); }; ログインやセッション管理にも同様の方法を使用できます。ソーシャル認証やパスワード回復などの追加機能は、back4appのダッシュボードを通じて設定できます。 ステップ 7 – webデプロイメントでのpreactフロントエンドの起動 back4appのwebデプロイメント機能を使用すると、githubリポジトリをリンクすることでpreactアプリケーションをホストできます。この部分では、プロダクションビルドを準備し、コードをコミットし、webデプロイメントと統合し、サイトをデプロイします。 7 1 プロダクションファイルを作成する ターミナルでプロジェクトディレクトリを開きます。 ビルドコマンドを実行します npm run build これにより、最適化された静的アセット(html、js、css、画像)を含む build フォルダーが生成されます。 3\ build フォルダーに index html ファイルと必要なアセットが含まれていることを確認します。 7 2 ソースコードを整理してコミットする リポジトリには、完全なpreactフロントエンドソースコードが含まれている必要があります。サンプルディレクトリ構造 basic crud app preact frontend/ ├── node modules/ ├── public/ │ └── index html ├── src/ │ ├── app js │ ├── parseconfig js │ └── components/ │ ├── itemslist js │ └── auth js ├── package json └── readme md 例のファイル src/parseconfig js // src/parseconfig js import parse from 'parse'; // enter your back4app credentials parse initialize('your application id', 'your javascript key'); parse serverurl = 'https //parseapi back4app com'; export default parse; src/app js // src/app js import { h } from 'preact'; import { useeffect, usestate } from 'preact/hooks'; import parse from ' /parseconfig'; function app() { const \[items, setitems] = usestate(\[]); const \[newitemtitle, setnewitemtitle] = usestate(""); const \[newitemdescription, setnewitemdescription] = usestate(""); const \[editingitemid, seteditingitemid] = usestate(null); const \[editingtitle, seteditingtitle] = usestate(""); const \[editingdescription, seteditingdescription] = usestate(""); const fetchitems = async () => { const items = parse object extend("items"); const query = new parse query(items); try { const results = await query find(); setitems(results); } catch (error) { console error("error fetching items ", error); } }; useeffect(() => { fetchitems(); }, \[]); const handleadditem = async () => { const items = parse object extend("items"); const item = new items(); item set("title", newitemtitle); item set("description", newitemdescription); try { await item save(); setnewitemtitle(""); setnewitemdescription(""); fetchitems(); } catch (error) { console error("error saving item ", error); } }; const handledeleteitem = async (id) => { try { const item = await parse object createwithoutdata("items", id); await item destroy(); fetchitems(); } catch (error) { console error("error deleting item ", error); } }; const starteditingitem = (item) => { seteditingitemid(item id); seteditingtitle(item get("title")); seteditingdescription(item get("description")); }; const handleupdateitem = async () => { try { const items = parse object extend("items"); const item = new items(); item id = editingitemid; item set("title", editingtitle); item set("description", editingdescription); await item save(); seteditingitemid(null); seteditingtitle(""); seteditingdescription(""); fetchitems(); } catch (error) { console error("error updating item ", error); } }; return ( \<div style={{ padding '2rem' }}> \<h1>items\</h1> \<div style={{ marginbottom '1rem' }}> \<h2>add item\</h2> \<input type="text" placeholder="title" value={newitemtitle} onchange={(e) => setnewitemtitle(e target value)} style={{ marginright '0 5rem' }} /> \<input type="text" placeholder="description" value={newitemdescription} onchange={(e) => setnewitemdescription(e target value)} style={{ marginright '0 5rem' }} /> \<button onclick={handleadditem}>add item\</button> \</div> \<h2>item list\</h2> \<ul> {items map((item) => ( \<li key={item id} style={{ marginbottom '1rem' }}> {editingitemid === item id ? ( \<div> \<input type="text" value={editingtitle} onchange={(e) => seteditingtitle(e target value)} style={{ marginright '0 5rem' }} /> \<input type="text" value={editingdescription} onchange={(e) => seteditingdescription(e target value)} style={{ marginright '0 5rem' }} /> \<button onclick={handleupdateitem}>save\</button> \<button onclick={() => seteditingitemid(null)} style={{ marginleft '0 5rem' }}> cancel \</button> \</div> ) ( \<div> \<strong>{item get("title")}\</strong> {item get("description")} \<button onclick={() => starteditingitem(item)} style={{ marginleft '1rem' }}> edit \</button> \<button onclick={() => handledeleteitem(item id)} style={{ marginleft '0 5rem' }}> delete \</button> \</div> )} \</li> ))} \</ul> \</div> ); } export default app; コードをgithubにコミットする gitリポジトリを初期化します(まだ行っていない場合): git init ソースファイルを準備する git add 変更をコミットする git commit m "initial commit of preact frontend source code" 新しいgithubリポジトリを作成します。例えば、 basic crud app preact frontend コードをプッシュする git remote add origin https //github com/your username/basic crud app preact frontend git git push u origin main 7 3 リポジトリをウェブデプロイメントに接続する back4appのダッシュボードのwebデプロイメントセクションに移動し、プロジェクトを開き( basic crud app preact )、次に選択します web deployment 指示に従ってgithubアカウントをリンクし、back4appがリポジトリにアクセスできるようにします。 リポジトリを選択します(例: basic crud app preact frontend )および適切なブランチを選択します(例: main )。 7 4 デプロイメント設定 追加設定を指定します ビルドコマンド 事前にビルドされた build フォルダーがない場合、ビルドコマンドを設定します(例: npm run build )。back4appはデプロイメント中にこのコマンドを実行します。 出力ディレクトリ 出力フォルダーを build として定義し、back4appが静的ファイルを識別できるようにします。 環境変数 アプリケーションに必要なapiキーや設定を追加します。 7 5 dockerを使用したpreactアプリケーションのコンテナ化 dockerを好む場合、リポジトリに次のような dockerfile を含めます # use an official node image for building from node 16 alpine as build \# set working directory workdir /app \# copy package files copy package json / \# install dependencies run npm install \# copy the source code copy \# build the app run npm run build \# use nginx to serve the built app from nginx\ stable alpine copy from=build /app/build /usr/share/nginx/html expose 80 cmd \["nginx", " g", "daemon off;"] back4appのwebデプロイ設定でdockerデプロイオプションを選択します。 7 6 アプリケーションのデプロイ 設定が完了したら、 デプロイ ボタンをクリックします。 back4appがコードを取得し、ビルドしてアプリケーションをデプロイする過程を監視します。 完了すると、back4appはアプリケーションがホストされているurlを提供します。 7 7 デプロイの確認 提供されたurlにアクセスして、ライブサイトを確認します。 すべての機能をテストして、ルートやアセットを含むすべての機能が正しく読み込まれることを確認します。 問題が発生した場合は、ブラウザのコンソールログとback4appのデプロイログを確認します。 ステップ8 – まとめと今後の方向性 素晴らしい仕事です!あなたはpreactとback4appを使用して完全なcrudアプリケーションを成功裏に開発しました。 「 basic crud app preact 」という名前のプロジェクトを設定し、堅牢なデータベースコレクションを定義し、効率的なデータ管理のためにadmin appを使用しました。 次に、preactのフロントエンドをバックエンドに接続し、厳格なアクセス制御を実装しました。 次は何ですか? 詳細ビュー、検索機能、リアルタイム更新などの追加機能でpreactアプリを強化しましょう。 cloud functionsやサードパーティapi統合など、より高度なバックエンドロジックを組み込みましょう。 最適化やカスタム設定についての深い洞察を得るために、 https //www back4app com/docs やその他のリソースを参照してください。 このチュートリアルに従うことで、back4appを使用してpreactアプリケーションのためのスケーラブルで安全なcrudバックエンドを構築するスキルを身につけました。コーディングを楽しみ、新しい機能を探求してください!
