Meteor.jsフレームワークを使ったRealtime Chatアプリのビルド
紹介
Meteor(Meteor.js)は、Node.jsをベースにしたフルスタックJavaScriptフレームワークであり、Webおよびモバイルアプリケーションの迅速かつ効率的な開発を可能にします。クライアントとサーバー間のスムーズな統合を最適化した設計により、Meteorはコード共有プロセスを簡素化するだけでなく、リアルタイムデータのエクスペリエンスを向上させます。
もし、迅速なアプリケーション開発のソリューションを探している場合、または最新のWeb技術に関する知識を広げたい場合は、この記事がMeteorについての概要と深い洞察を提供します。
Meteorの特徴
このセクションでは、Meteorの際立った特徴をさらに詳しく探り、このフレームワークがWebおよびモバイル開発分野でどのように差別化され、ユニークであるかを見ていきます。
クライアントとサーバーとのスムーズな統合:Meteorは自動的なデータ同期モデルを提供し、複雑なデータ同期コードを書く必要なく、クライアントとサーバーの両方でデータをリアルタイムに更新することを可能にします。
クライアントとサーバーとのコード共有:Meteorを使用すると、コード共有が容易になり、アプリケーションの開発および保守プロセスを最適化できます。
リアルタイムデータの更新:MeteorはDDP(Distributed Data Protocol)を使用してクライアントとサーバーとのデータを同期化し、データを迅速かつスムーズに更新できるアプリケーションを実現します。
強力なエコシステム:Meteorは、MongoDBとの統合から、Meteor独自のホスティングサービスであるGalaxyを使用したアプリケーションのデプロイまで、数千のパッケージやツールを備えた豊富なエコシステムを提供します。
ホットコードプッシュ機能:この機能により、開発者はユーザー体験を妨げることなくアプリケーションを更新することができ、アプリの保守と更新において大きな利点を提供します。
マルチプラットフォーム対応:一度コードを書くことで、それをWebアプリとしてデプロイしたり、AndroidやiOS向けのモバイルアプリとしてビルドしたりすることができます。
Meteor.jsで開始
Meteorを始めるには、Node.jsが既にインストールされていることを確認する必要があります。現在、MeteorはNode.jsのバージョン10~14をサポートしており、Meteor 3.0は、最新のNode.jsバージョンをサポートするために開発されています。
Meteorインストール
Windows、Linux、OS X
上記のプラットフォームにおいて、以下のコマンドをターミナルで実行することでMeteorをインストールできます。
npm install -g meteor
また、LinuxとOS Xでは、curl
経由で以下のコマンドを使用してMeteorをインストールすることもできます。
curl https://install.meteor.com/ | sh
簡単なリアルタイムチャットアプリの作成
Meteor.jsについてさらに学ぶために、以下のように、簡単なリアルタイムチャットプロジェクトを一緒に作成してみましょう!
1. プロジェクトの初期化
プロジェクトを迅速にセットアップするには、meteor create
コマンドに--blaze
オプションを付けて実行します。ここでは、プロジェクト名を「simple-chat-meteor」とします。
meteor create --blaze simple-chat-meteor
初期化が成功した後、ターミナルに次のようなメッセージが表示されます。
アプリケーションを実行するには、プロジェクトディレクトリへ辿って、meteor run
コマンドを使用します。
cd simple-chat-meteor meteor run
ブラウザを開き、http://localhost:3000 にアクセスすると、そのアプリケーションが見えます。
2. プロジェクト構成
.meteor:Meteorアプリケーションにおいて最も重要なディレクトリです。このディレクトリには、Meteorアプリケーションのコア設定ファイルと以下のようなサブディレクトリが含まれています。
- local:アプリケーションのローカルデータやログファイルを格納する
- packages:アプリケーションに使われているライブラリのリストを格納する
- platforms:アプリケーションが対応しているプラットフォームを格納する
- versions:アプリケーションに使われているライブラリのバージョン情報を保存するファイルです。
client:アプリケーションのクライアント側のソースコードを格納するディレクトリであり、以下のものが含まれます。
- main.css:クライアント側のスタイルを定義する主なCSSファイル
- main.html:アプリケーションのレイアウトやテンプレートを定義する原点となる主なHTMLファイル
- main.js:Blazeテンプレートのイベントやヘルパーを定義するところとなるクライアント用の主なJavaScriptファイル
server:アプリケーションのサーバー側ソースコードを格納するディレクトリであり、以下のものが含まれます。
- main.js:パブリケイションやメソッドの設定、およびサーバー初期化の設定を行うところとなるサーバー用の主なJavaScriptファイル
tests:アプリケーションのテストファイルを格納するディレクトリです。
node_modules:プロジェクトが依存しているNPMパッケージを格納するディレクトリです。
3. 各機能の実装
このセクションでは、Meteorチャットアプリケーションに機能を追加するために必要な手順を説明します。これには、ユーザーインターフェースの設定、イベント処理、ログインおよびログアウト機能の構築が含まれます。
ユーザーインターフェースの設定
client/main.htmlファイルでは、チャットアプリの基本的なHTML構造を定義します。これには、タイトルやモバイルデバイスでの表示を最適化するためのmetaタグが含まれます。
<head> <title>Simple Chat Meteor</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <meta name="viewport" content="width=device-width, height=device-height, viewport-fit=cover, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" /> <meta name="mobile-web-app-capable" content="yes"/> <meta name="apple-mobile-web-app-capable" content="yes"/> </head>
client/main.jsファイルでは、UIチャットを初期化するためにChat.jsファイルをインポートします。
import '../imports/ui/Chat/Chat.js';
イベントとデータの処理
importsディレクトリを作成して、UIとロジックの毎に分けられるソースコードを格納します。
imports/ui/Chat内に、Chat.htmlファイルを作成し、チャットアプリケーションのユーザーインターフェースを定義します。
Blazeテンプレートを使用して、中身と表示ロジックを整理します。
<body> {{> chatContainer}} </body> <template name="chatContainer"> <div class="chat-container"> <div class="chat-header"> <h2>Simple Chat Meteor</h2> </div> {{> chatContent}} {{> chatInput}} </div> </template> <template name="chatContent"> <div class="chat-content"> {{#each chats}} <div class="message"> <div class="username">{{ username }}</div> <div class="message-content">{{ messageText }}</div> </div> {{/each}} </div> </template> <template name="chatInput"> <div class="chat-input"> <input id="message" type="text" placeholder="Input your message..." /> <button id="sendMessage">Send</button> </div> </template>
chatContainer:アプリケーションのヘッダー(chat-header)とチャット内容部分といったチャットアプリケーションのインターフェースの全部を含むメインテンプレートです。
chatContent:チャット内容を表示するためのより小さいなテンプレートであり、chats(各メッセージ)分、繰り返して、username(送信した者の名前)とmessageText(メッセージ内容)を表示させます。
chatInput:ユーザーが新しいメッセージを送信できるようにするための他のテンプレートであり、メッセージ内容を入力するための入力項目と、メッセージを送信するためのSendボタンがあります。
client/main.cssファイルに以下のCSSを追加します。
:root { --main-bg-color: #f0f2f5; --chat-bg-color: #fff; --highlight-color: #f69914; --text-color-white: #fff; --border-color: #ddd; --input-border-color: #ccc; --hover-bg-color: #0056b3; } body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; overflow: hidden; margin: 0; background-color: var(--main-bg-color); } .chat-container { height: 100%; width: 600px; border: 1px solid var(--border-color); background-color: var(--chat-bg-color); display: flex; flex-direction: column; } .chat-header { display: flex; justify-content: space-between; align-items: center; background-color: var(--highlight-color); color: var(--text-color-white); height: 68px; padding: 0px 10px; } .chat-header button#logout { height: 30px; background-color: transparent; cursor: pointer; color: var(--text-color-white); border: 1px solid var(--chat-bg-color); border-radius: 10px; } .chat-content { padding: 10px; height: calc(100vh - 90px - 57px); overflow-y: auto; gap: 10px; } .chat-content .message { background-color: #f1f1f1; padding: 10px; border-radius: 10px; display: flex; flex-direction: column; } .chat-content .message:not(:first-child) { margin-top: 10px; } .chat-content .message .username { font-weight: bold; color: var(--highlight-color); } .chat-content .message .message-content { margin-top: 5px; } .chat-input { display: flex; padding: 10px; height: 57px; box-sizing: border-box; } .chat-input input { flex: 1; padding: 10px; margin-right: 10px; border: 1px solid var(--input-border-color); border-radius: 4px; } .chat-input button { padding: 10px; background-color: var(--highlight-color); color: white; border: none; border-radius: 4px; cursor: pointer; } .chat-input button:hover { background-color: var(--hover-bg-color); } .auth-container { background-color: white; padding: 40px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); width: 300px; } .auth-container h2 { text-align: center; margin-bottom: 20px; } .auth-container p span { text-decoration: underline; color: var(--hover-bg-color); cursor: pointer; } #loginForm .input-group, #signupForm .input-group { margin-bottom: 15px; display: flex; flex-direction: column; } #loginForm .input-group label, #signupForm .input-group label { margin-bottom: 5px; } #loginForm .input-group input, #signupForm .input-group input { padding: 10px; border: 1px solid var(--border-color); border-radius: 4px; } #loginForm button, #signupForm button { background-color: orange; color: white; padding: 10px; border: none; border-radius: 4px; cursor: pointer; width: 100%; } #loginForm button:hover, #signupForm button:hover { background-color: darkorange; }
imports/api内に、ChatsCollection.jsを作成します。
import { Mongo } from 'meteor/mongo'; export const ChatsCollection = new Mongo.Collection('chats');
imports/api内に、ChatsPublications.jsを作成します。
import { Meteor } from "meteor/meteor"; import { ChatsCollection } from "./ChatsCollection"; Meteor.publish("chats", function () { return ChatsCollection.find({}, { sort: { createdAt: -1 } }); });
次に、Meteorでチャットのデータベースに接続し、サーバーからチャットデータを登録して、ユーザーインターフェースでメッセージを時系列順に表示するようにします。
imports/ui/Chat/Chat.jsに以下のコードを追加します。
import { Template } from "meteor/templating"; import { ChatsCollection } from "/imports/api/ChatsCollection"; import "./Chat.html"; Meteor.subscribe("chats"); Template.chatContent.helpers({ chats() { return ChatsCollection.find({}, { sort: { createdAt: 1 } }); }, });
server/main.jsのコードを以下のように置き換えます。
import { Meteor } from "meteor/meteor"; import { ChatsCollection } from "/imports/api/ChatsCollection"; import '/imports/api/ChatsPublications'; Meteor.startup(() => { if (ChatsCollection.find().count() === 0) { ChatsCollection.insert({ messageText: 'Welcome to the chat app!', createdAt: new Date(), username: "Admin", }); } });
目的としは、サーバー起動時にメッセージが存在しない場合、デフォルトのメッセージを追加することです。
→ meteor run
コマンドを使用して、Meteor.js アプリケーションを起動します。その後、http://localhost:3000にアクセスして結果を確認できます。
メッセージ送信機能の実装
imports/ui/Chat/Chat.jsに以下のコードを追加します。
... Template.body.events({ "click #sendMessage": function () { const messageElement = document.querySelector("#message"); if (messageElement.value.trim()) { Meteor.call("chats.sendMessage", messageElement.value.trim()); messageElement.value = ""; } }, });
imports/ap内に、ChatsMethods.jsを作成して、以下のコードを追加します。
import { Meteor } from 'meteor/meteor'; import { ChatsCollection } from "./ChatsCollection"; Meteor.methods({ 'chats.sendMessage'(message) { ChatsCollection.insert({ messageText: message, createdAt: new Date(), username: "Admin" }); } });
次に、作成したてのメソッドをserver/main.jsファイルにインポートします。
... import '/imports/api/ChatsMethods'; ...
ここで任意のメッセージを送信してみましょう!
ログイン、登録、ログアウト機能の実装
以下のコマンドを使用して、accounts-passwordとbcryptパッケージをインストールします
meteor add accounts-password meteor npm install --save bcrypt
imports/ui/Auth内に、Auth.htmlを作成して、以下のコードを追加します。
<template name="authContainer"> {{> Template.dynamic template=currentView}} </template> <template name="loginContainer"> <div class="auth-container" > <h2>Login</h2> <form id="loginForm"> <div class="input-group"> <label for="username">Username</label> <input type="text" id="username" name="username" required> </div> <div class="input-group"> <label for="password">Password</label> <input type="password" id="password" name="password" required> </div> <button type="submit">Login</button> </form> <p>Don’t have an account yet? <span>Sign up</span> </p> </div> </template> <template name="signupContainer"> <div class="auth-container" > <h2>Sign up</h2> <form id="signupForm"> <div class="input-group"> <label for="username">Username</label> <input type="text" id="username" name="username" required> </div> <div class="input-group"> <label for="password">Password</label> <input type="password" id="password" name="password" required> </div> <div class="input-group"> <label for="confirmPassword">Confirm Password</label> <input type="password" id="rePassword" name="confirmPassword" required> </div> <button type="submit">Sign up</button> </form> <p>Already have an account? <span>Login here</span> </p> </div> </template>
imports/ui/Auth内に、Auth.jsを作成して、以下のコードを追加します。
import { Template } from "meteor/templating"; import "./Auth.html"; import { ReactiveVar } from "meteor/reactive-var"; currentView = new ReactiveVar("loginContainer"); Template.authContainer.helpers({ currentView: function () { return currentView.get(); }, }); Template.loginContainer.events({ "click span": function (e) { e.preventDefault(); currentView.set("signupContainer"); }, "submit #loginForm"(e) { e.preventDefault(); const target = e.target; const username = target.username.value; const password = target.password.value; Meteor.loginWithPassword(username, password, (err) => { if (err) { alert(err); } }); }, }); Template.signupContainer.events({ "click span": function (e) { e.preventDefault(); currentView.set("loginContainer"); }, "submit #signupForm"(e) { e.preventDefault(); const target = e.target; const username = target.username.value; const password = target.password.value; const confirmPassword = target.confirmPassword.value; if (password !== confirmPassword) { alert("Password do not match"); return; } Accounts.createUser( { username, password, }, (err) => { if (err) { alert(err); } } ); }, });
imports/ui/Chat/Chat.htmlで、ユーザーがログインしていることを確認し、ログアウトボタンを追加します。
<body> {{#if isUserLogged}} {{> chatContainer}} {{else}} {{> authContainer}} {{/if}} </body> ... <div class="chat-header"> <h2>Simple Chat Meteor</h2> <button id="logout">Logout</button> </div> ...
imports/ui/Chat/Chat.jsで、ユーザーがログインしていることを確認し、ログアウト処理を行います。
import "../Auth/Auth.js" ... Template.body.helpers({ isUserLogged() { return !!Meteor.userId() && !Meteor.loggingIn(); }, }); Template.body.events({ "click #sendMessage": function () { const messageElement = document.querySelector("#message"); if (messageElement.value.trim()) { Meteor.call("chats.sendMessage", messageElement.value.trim()); messageElement.value = ""; } }, "click #logout": function () { Meteor.logout(); }, });
server/main.jsで、アカウント「admin」を確認して存在しなければ追加し、デフォルトメッセージに「username」を追加します。
import { Meteor } from "meteor/meteor"; import '/imports/api/ChatsMethods'; import '/imports/api/ChatsPublications'; import { ChatsCollection } from "/imports/api/ChatsCollection"; import { Accounts } from 'meteor/accounts-base'; const SEED_USERNAME = "admin"; const SEED_PASSWORD = "admin"; Meteor.startup(() => { if (!Accounts.findUserByUsername(SEED_USERNAME)) { Accounts.createUser({ username: SEED_USERNAME, password: SEED_PASSWORD, }); } const user = Accounts.findUserByUsername(SEED_USERNAME); if (ChatsCollection.find().count() === 0) { ChatsCollection.insert({ messageText: 'Welcome to the chat app!', createdAt: new Date(), username: user.username, }); } });
同様に、imports/api/ChatsMethods.jsで「sendMessage」メソッドに「username」を追加します。
import { Meteor } from 'meteor/meteor'; import { ChatsCollection } from "./ChatsCollection"; Meteor.methods({ 'chats.sendMessage'(message) { const username = Meteor.user()?.username; ChatsCollection.insert({ messageText: message, createdAt: new Date(), username: username }); } });
成果物を見ましょう!!
未ログイン状態でログイン画面が表示されます。
サインアップ画面が出ます。
Express.jsと比較
拡張性
- Meteor.jsは、開発を迅速かつ容易にするために、豊富な機能と事前に構築されたコンポーネントを備えた「開発ツールキット」を提供します。ただし、大規模なプロジェクトではカスタマイズや拡張性が制限される場合があります。
- Express.jsは、柔軟なフレームワークであり、開発者がアプリケーション構造を自由に設計できる環境を提供します。これにより、拡張性の高い大規模で複雑なプロジェクトに最適です。
リアルタイム通信
- Meteor.jsは、クライアントとサーバー間のリアルタイム通信機能を標準で備えており、ページをリロードせずにデータを即座に更新できます。
- Express.jsは、同様の機能を実現するには、サードパーティライブラリを追加で統合する必要があり、開発工数が膨らみます。
データベース統合
- Meteor.jsは、MongoDBと密接に統合されており、その利用を最適化しています。そのためデータ管理が簡単になりますが、選択肢が制限される場合があります。
- Express.jsは、SQLからNoSQLまで多様なデータベースとの接続をサポートしており、プロジェクトの要件に応じて柔軟に選択できます。
コミュニティとエコシステム
- Meteor.jsは、コミュニティは比較的小規模ですが、開発ニーズをサポートするための十分なパッケージやツールが提供されています。
- Express.jsは、大規模で多様なコミュニティがあり、数千ものライブラリや追加ツールが存在します。これにより、アプリケーションの拡張や改善に多くの選択肢を提供します。
開発速度と習得難易度
- Meteor.jsは、多くの機能があらかじめ統合されているため、設定や管理作業を最小限に抑え、アプリケーション開発の速度を向上させます。学習曲線が比較的緩やかで、初心者に適しています。
- Express.jsは、柔軟で高度にカスタマイズ可能なアプローチを提供しますが、設定に時間がかかる場合があります。それでも、長期的なプロジェクト開発では大きなメリットがあります。Node.jsの理解やミドルウェアの統合方法に関する知識が必要で、経験豊富な開発者に適しています。
結論
これまでの分析からして、Express.jsとMeteorはそれぞれ独自の長所と短所を持ち、異なる種類のプロジェクトや開発ニーズに適していることがわかります。
Express.jsは、高いカスタマイズ性と大規模な拡張性が必要なプロジェクトに適しています。特に、複雑で多様なデータベースや、大規模なエコシステムと豊富なライブラリやツールが求められるプロジェクトに最適です。
それに対して、Meteor.jsは、迅速かつ簡単な開発を求める場合に最適な選択肢です。特にリアルタイムアプリケーションや、MongoDBを必要とする小規模から中規模のプロジェクトに適しています。設定やインフラ管理に時間をかけず、アイデアの実現に集中したい開発者に向いています。
要約すると、Express.jsとMeteorの選択は、プロジェクトの具体的な要件、開発チームのスキルや経験、プロジェクトの目標やスケジュールに依存します。どちらの技術も独自の強みを持っており、適切な技術を選択することでプロジェクトの成功に大きく貢献します。