Merge branch 'devel' into feature/oauth-config-update

This commit is contained in:
Italo José
2025-12-02 14:47:25 -03:00
committed by GitHub
116 changed files with 5992 additions and 310 deletions

View File

@@ -0,0 +1,198 @@
// Tests for inactive-issues.js using Node's built-in test runner (node:test)
// We only care about the last comments (per user instruction), so we don't need pagination logic.
const { test, beforeEach } = require('node:test');
const assert = require('node:assert');
const path = require('node:path');
// Load the script dynamically so we can pass mocks.
const scriptPath = path.join(__dirname, '..', 'inactive-issues.js');
// Helper to advance days
const daysAgo = (days) => {
const d = new Date();
d.setUTCDate(d.getUTCDate() - days);
return d.toISOString();
};
// Factory for github REST mock structure
function buildGithubMock({ issues, commentsByIssue }) {
return {
rest: {
issues: {
listForRepo: async ({ page, per_page }) => {
// simple pagination slice
const start = (page - 1) * per_page;
const end = start + per_page;
return { data: issues.slice(start, end) };
},
listComments: async ({ issue_number }) => {
return { data: commentsByIssue[issue_number] || [] };
},
createComment: async ({ issue_number, body }) => {
// push comment to structure to allow assertions on side effects if needed
const arr = commentsByIssue[issue_number] || (commentsByIssue[issue_number] = []);
arr.push({
id: Math.random(),
body,
created_at: new Date().toISOString(),
user: { login: 'github-actions[bot]', type: 'Bot' }
});
return {};
},
addLabels: async ({ issue_number, labels }) => {
const issue = issues.find(i => i.number === issue_number);
if (issue) {
(issue.labels || (issue.labels = [])).push(...labels.map(l => ({ name: l })));
}
return {};
}
}
}
};
}
// Wrap script invocation for reuse
async function runScript({ issues, commentsByIssue }) {
delete require.cache[require.resolve(scriptPath)];
const fn = require(scriptPath);
const github = buildGithubMock({ issues, commentsByIssue });
await fn({ github, context: { repo: { owner: 'meteor', repo: 'meteor' } } });
return { issues, commentsByIssue };
}
let baseIssueNumber = 1000;
function makeIssue({ daysSinceHumanActivity, isPR = false, labels = [], user = 'user1' }) {
// We'll simulate by setting created_at to the human activity date if no comments.
const updated_at = daysAgo(daysSinceHumanActivity);
return {
number: baseIssueNumber++,
pull_request: isPR ? {} : undefined,
labels: labels.map(n => ({ name: n })),
user: { login: user },
created_at: daysAgo(daysSinceHumanActivity),
updated_at
};
}
// TESTS
beforeEach(() => {
baseIssueNumber = 1000;
});
test('60 days inactivity -> adds reminder comment (no prior reminder)', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 60 });
const issues = [issue];
const commentsByIssue = { [issue.number]: [] }; // no comments
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 1, 'Should have 1 reminder comment');
assert.match(botComments[0].body, /60 days/);
assert.ok(!issue.labels.some(l => l.name === 'idle'), 'Should not label yet');
});
test('60 days inactivity but already reminded -> no duplicate comment', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 65 });
const issues = [issue];
const commentsByIssue = {
[issue.number]: [
{
id: 1,
body: '👋 @user1 This issue has been open with no human activity for 60 days. Is this issue still relevant? If there is no human response or activity within the next 30 days, this issue will be labeled as `idle`.',
created_at: daysAgo(5), // 5 days ago bot comment (means last human is 65 days, bot after human)
user: { login: 'github-actions[bot]', type: 'Bot' }
}
]
};
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 1, 'Should still have only the existing reminder');
});
test('90 days inactivity -> label + comment', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 95 });
const issues = [issue];
const commentsByIssue = { [issue.number]: [] };
await runScript({ issues, commentsByIssue });
assert.ok(issue.labels.some(l => l.name === 'idle'), 'Should add idle label');
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 1, 'Should comment when labeling');
assert.match(botComments[0].body, /90 days/i);
});
test('90 days inactivity but already labeled -> no action', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 100, labels: ['idle'] });
const issues = [issue];
const commentsByIssue = { [issue.number]: [] };
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 0, 'Should not comment again');
});
test('90 days inactivity but already labeled `in-development` -> no action', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 100, labels: ['in-development'] });
const issues = [issue];
const commentsByIssue = { [issue.number]: [] };
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 0, 'Should not comment again');
});
test('Human reply after reminder resets cycle (no immediate labeling)', async () => {
// Scenario: last human activity 10 days ago, bot commented 40 days ago (which was 50 days after original). Should NOT comment again or label.
const issue = makeIssue({ daysSinceHumanActivity: 10 });
const issues = [issue];
const commentsByIssue = {
[issue.number]: [
{
id: 1,
body: '👋 @user1 This issue has been open with no human activity for 60 days... ',
created_at: daysAgo(50),
user: { login: 'github-actions[bot]', type: 'Bot' }
},
{
id: 2,
body: 'I am still seeing this problem',
created_at: daysAgo(10),
user: { login: 'some-human', type: 'User' }
}
]
};
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => c.user.login === 'github-actions[bot]');
assert.equal(botComments.length, 1, 'Should not add a new bot comment');
assert.ok(!issue.labels.some(l => l.name === 'idle'), 'Should not label');
});
test('Only bot comments (no human ever) counts from creation date', async () => {
const issue = makeIssue({ daysSinceHumanActivity: 61 });
const issues = [issue];
const commentsByIssue = {
[issue.number]: [
{
id: 1,
body: 'Automated maintenance notice',
created_at: daysAgo(30),
user: { login: 'github-actions[bot]', type: 'Bot' }
}
]
};
await runScript({ issues, commentsByIssue });
const botComments = commentsByIssue[issue.number].filter(c => /60 days/.test(c.body));
assert.equal(botComments.length, 1, 'Should add a 60-day reminder');
});

View File

@@ -1,190 +1,200 @@
/**
* Mark issues as idle after a period of inactivity
* and post reminders after a shorter period of inactivity.
*
* 1. Issues with no human activity for 60 days get a reminder comment.
* 2. Issues with no human activity for 90 days get labeled as "idle" and get a comment.
*
* Human activity is defined as any comment from a non-bot user.
*
* This script is intended to be run as a GitHub Action on a schedule (e.g., daily).
*/
module.exports = async ({ github, context }) => {
const daysToComment = 60;
const daysToLabel = 90;
const idleTimeComment = daysToComment * 24 * 60 * 60 * 1000;
const idleTimeLabel = daysToLabel * 24 * 60 * 60 * 1000;
const now = new Date();
const idleTimeComment = daysToComment * 24 * 60 * 60 * 1000; // 60 days in milliseconds
const idleTimeLabel = daysToLabel * 24 * 60 * 60 * 1000; // 90 days in milliseconds
// Function to fetch issues until we find recently updated ones
const BOT_LOGIN = 'github-actions[bot]';
const REMINDER_PHRASE = 'Is this issue still relevant?';
const COMMENT_60_TEMPLATE = (login) =>
`👋 @${login} This issue has been open with no human activity for ${daysToComment} days. Is this issue still relevant? If there is no human response or activity within the next ${daysToLabel - daysToComment} days, this issue will be labeled as \`idle\`.`;
const COMMENT_90_TEXT =
'This issue has been automatically labeled as `idle` due to 90 days of inactivity (no human interaction). If this is still relevant or if someone is working on it, please comment or add `in-development` label.';
// Fetch all open issues
async function fetchAllIssues() {
let allIssues = [];
let page = 1;
let hasNextPage = true;
const now = new Date();
const minInactivity = idleTimeComment; // 60 days in milliseconds
while (hasNextPage) {
const response = await github.rest.issues.listForRepo({
const per_page = 100;
const results = [];
let keepGoing = true;
while (keepGoing) {
const { data } = await github.rest.issues.listForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
per_page: 100,
page: page,
per_page,
page,
sort: 'updated',
direction: 'asc' // Oldest updated first
direction: 'asc'
});
// Check if the most recently updated issue on this page is too recent
let recentIssueFound = false;
if (response.data.length > 0) {
// Check the last issue on the page (most recently updated)
const lastIssue = response.data[response.data.length - 1];
const lastIssueUpdatedAt = new Date(lastIssue.updated_at);
const timeSinceLastIssueUpdate = now.getTime() - lastIssueUpdatedAt.getTime();
if (timeSinceLastIssueUpdate < minInactivity) {
// This page already has issues that are too recent, filter them out
const filteredIssues = response.data.filter(issue => {
const issueUpdatedAt = new Date(issue.updated_at);
const timeSinceUpdate = now.getTime() - issueUpdatedAt.getTime();
return timeSinceUpdate >= minInactivity;
});
allIssues = allIssues.concat(filteredIssues);
recentIssueFound = true;
hasNextPage = false;
} else {
// All issues on this page are old enough, keep them all
allIssues = allIssues.concat(response.data);
}
}
// Stop if we found recent issues or reached the end of pagination
if (recentIssueFound) {
hasNextPage = false;
} else if (response.data.length < 100) {
hasNextPage = false;
if (!data.length) break;
results.push(...data);
if (data.length < per_page) {
keepGoing = false;
} else {
page++;
// Small delay to avoid hitting rate limits
await new Promise(resolve => setTimeout(resolve, 100));
await new Promise((r) => setTimeout(r, 120));
}
}
return allIssues;
return results;
}
// Fetch all issues
const allIssues = await fetchAllIssues();
let processedCount = 0;
let commentedCount = 0;
let labeledCount = 0;
for (const issue of allIssues) {
processedCount++;
// Skip pull requests
if (issue.pull_request) {
continue;
}
// Skip issues that already have the idle label
if (issue.labels.some(label => label.name === 'idle')) {
continue;
}
// Get latest comment or update date
const issueUpdatedAt = new Date(issue.updated_at);
const timeSinceUpdate = now.getTime() - issueUpdatedAt.getTime();
// Handle 60-day idle issues (comment)
if (timeSinceUpdate > idleTimeComment && timeSinceUpdate <= idleTimeLabel) {
// Check if bot already commented to avoid duplicate comments
const comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
per_page: 100
});
// Check if there's a recent bot comment
const botCommented = comments.data.some(comment => {
const commentDate = new Date(comment.created_at);
const timeSinceComment = now.getTime() - commentDate.getTime();
const isBot = comment.user.login === 'github-actions[bot]';
const isRecent = timeSinceComment < idleTimeComment;
const hasRightContent = comment.body.includes('Is this issue still relevant?');
return isBot && isRecent && hasRightContent;
});
if (!botCommented) {
try {
const result = await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: `👋 @${issue.user.login} This issue has been open for 60 days with no activity. Is this issue still relevant? If there is no response or activity within the next 30 days, this issue will be labeled as \`idle\`.`
});
commentedCount++;
} catch (error) {
// Add retry logic
try {
// Wait for 5 seconds before retrying
await new Promise(resolve => setTimeout(resolve, 5000));
const retryResult = await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: `👋 @${issue.user.login} This issue has been open for 60 days with no activity. Is this issue still relevant? If there is no response or activity within the next 30 days, this issue will be labeled as \`idle\`.`
});
commentedCount++;
} catch (retryError) {
// Failed retry, continue with other issues
}
}
// analyse comments to find last human activity and if a reminder was already posted after that
async function analyzeComments(issueNumber, issueCreatedAt) {
const commentsResp = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100
});
const comments = commentsResp.data;
let lastHumanActivity = null;
for (let i = comments.length - 1; i >= 0; i--) {
const c = comments[i];
const isBot = c.user?.type === 'Bot' || c.user?.login === BOT_LOGIN;
if (!isBot) {
lastHumanActivity = new Date(c.created_at);
break;
}
}
// Handle 90-day idle issues (add label)
else if (timeSinceUpdate > idleTimeLabel) {
// Check if the issue has the idle label
if (!issue.labels.some(label => label.name === 'idle')) {
if (!lastHumanActivity) {
lastHumanActivity = new Date(issueCreatedAt);
}
const hasReminderAfterLastHuman = comments.some(
(c) =>
c.user?.login === BOT_LOGIN &&
c.body?.includes(REMINDER_PHRASE) &&
new Date(c.created_at) > lastHumanActivity
);
return { lastHumanActivity, hasReminderAfterLastHuman };
}
const issues = await fetchAllIssues();
let processed = 0;
let commented = 0;
let labeled = 0;
let skippedPR = 0;
for (const issue of issues) {
processed++;
if (issue.pull_request) {
skippedPR++;
continue;
}
if (issue.labels.some((l) => l.name === 'idle' || l.name === 'in-development')) {
continue;
}
let analysis;
try {
analysis = await analyzeComments(issue.number, issue.created_at);
} catch (err) {
continue; // fail to get comments, skip
}
const { lastHumanActivity, hasReminderAfterLastHuman } = analysis;
const inactivityMs = now.getTime() - lastHumanActivity.getTime();
// 90+ days => label + comment
if (inactivityMs >= idleTimeLabel) {
try {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: ['idle']
});
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: COMMENT_90_TEXT
});
labeled++;
continue;
} catch (err) {
// retry simples
try {
// Add the label
const labelResult = await github.rest.issues.addLabels({
await new Promise((r) => setTimeout(r, 5000));
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: ['idle']
});
// Add a comment when labeling as idle
const commentResult = await github.rest.issues.createComment({
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: `This issue has been automatically labeled as \`idle\` due to 90 days of inactivity. If this issue is still relevant, please comment to reactivate it.`
body: COMMENT_90_TEXT
});
labeledCount++;
} catch (error) {
// Add retry logic with exponential backoff
try {
// Wait for 5 seconds before retrying
await new Promise(resolve => setTimeout(resolve, 5000));
const retryLabelResult = await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
labels: ['idle']
});
// Retry adding comment
const retryCommentResult = await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: `This issue has been automatically labeled as \`idle\` due to 90 days of inactivity. If this issue is still relevant, please comment to reactivate it.`
});
labeledCount++;
} catch (retryError) {
// Continue with other issues if retry fails
}
}
labeled++;
} catch {}
continue;
}
}
// 60-89 days => comment (once)
if (
inactivityMs >= idleTimeComment &&
inactivityMs < idleTimeLabel &&
!hasReminderAfterLastHuman
) {
const body = COMMENT_60_TEMPLATE(issue.user.login);
try {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body
});
commented++;
} catch (err) {
try {
await new Promise((r) => setTimeout(r, 5000));
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body
});
commented++;
} catch {}
}
}
}
// Log summary for CI
console.log(
JSON.stringify(
{ processed, commented, labeled, skippedPR },
null,
2
)
);
};

View File

@@ -155,7 +155,7 @@ Learn how we use GitHub labels [here](LABELS.md)
## Documentation
If you'd like to contribute to Meteor's documentation, head over to https://docs.meteor.com or https://guide.meteor.com and if you find something that could be better click in "Edit on GitHub" footer to edit and submit a PR.
If you'd like to contribute to Meteor's documentation, head over to https://docs.meteor.com/about/contributing.html for guidelines.
## Blaze

View File

@@ -677,7 +677,7 @@ Your project should be a git repository as the commit hash is going to be used t
The `cache-build` option is available since Meteor 1.11.
{% endpullquote %}
With the argument `--container-size` you can change your app's container size using the deploy command. The valid arguments are: `tiny`, `compact`, `standard`, `double`, `quad`, `octa`, and `dozen`. One more thing to note here is that the `--container-size` flag can only be used when the `--plan` option is already specified, otherwise using the `--container-size` option will throw an error with the message : `Error deploying application: Internal error`. To see more about the difference and prices of each one you can check [here](https://www.meteor.com/cloud#pricing-section).
With the argument `--container-size` you can change your app's container size using the deploy command. The valid arguments are: `tiny`, `compact`, `standard`, `double`, `quad`, `octa`, and `dozen`. One more thing to note here is that the `--container-size` flag can only be used when the `--plan` option is already specified, otherwise using the `--container-size` option will throw an error with the message : `Error deploying application: Internal error`. To see more about the difference and prices of each one you can check [here](https://galaxycloud.app/meteorjs/pricing).
{% pullquote warning %}
The `--container-size` option is available since Meteor 2.4.1.

View File

@@ -194,7 +194,7 @@ MONGO_URL=mongodb://localhost:27017/myapp ROOT_URL=http://my-app.com PORT=3000 n
```
* `ROOT_URL` is the base URL for your Meteor project
* `PORT` is the port at which the application is running
* `PORT` is the port at which the application is running
* `MONGO_URL` is a [Mongo connection string URI](https://docs.mongodb.com/manual/reference/connection-string/) supplied by the MongoDB provider.
@@ -322,7 +322,7 @@ Galaxy's UI provides a detailed logging system, which can be invaluable to deter
If you really want to understand the ins and outs of running your Meteor application, you should use an Application Performance Monitoring (APM) service. There are multiple services designed for Meteor apps:
- [Meteor APM](https://www.meteor.com/cloud)
- [Meteor APM](https://galaxycloud.app/)
- [Monti APM](https://montiapm.com/)
- [Meteor Elastic APM](https://github.com/Meteor-Community-Packages/meteor-elastic-apm)

View File

@@ -3,10 +3,10 @@ title: Performance improvements
description: How to optimize your Meteor application for higher performance when you start growing.
---
This guide focuses on providing you tips and common practices on how to improve performance of your Meteor app (sometimes also called scaling).
It is important to note that at the end of the day Meteor is a Node.js app tied closely to MongoDB,
so a lot of the problems you are going to encounter are common to other Node.js and MongoDB apps.
Also do note that every app is different so there are unique challenges to each, therefore
This guide focuses on providing you tips and common practices on how to improve performance of your Meteor app (sometimes also called scaling).
It is important to note that at the end of the day Meteor is a Node.js app tied closely to MongoDB,
so a lot of the problems you are going to encounter are common to other Node.js and MongoDB apps.
Also do note that every app is different so there are unique challenges to each, therefore
practices describe in this guide should be used as a guiding posts rather than absolutes.
This guide has been heavily inspired by [Marcin Szuster's Vazco article](https://www.vazco.eu/blog/how-to-optimize-and-scale-meteor-projects), the official [Meteor Galaxy guide](https://galaxy-guide.meteor.com/),
@@ -15,11 +15,11 @@ and talk by Paulo Mogollón's talk at Impact 2022 titled ["First steps on scalin
<h2 id="performance-monitoring">Performance monitoring</h2>
Before any optimization can take place we need to know what is our problem. This is where APM (Application Performance Monitor) comes in.
If you are hosting on Galaxy then this is automatically included in the [Professional plan](https://www.meteor.com/cloud/pricing)
and you can learn more about in its [own dedicated guide article](https://cloud-guide.meteor.com/apm-getting-started.html).
For those hosting outside of Galaxy the most popular solution is to go with [Monti APM](https://montiapm.com/) which shares
all the main functionality with Galaxy APM. You can also choose other APM for Node.js, but they will not show you Meteor
specific data that Galaxy APM and Monti APM specialize in. For this guide we will focus on showing how to work with Galaxy APM,
If you are hosting on Galaxy then this is automatically included in the [Professional plan](https://galaxycloud.app/meteorjs/pricing)
and you can learn more about in its [own dedicated guide article](https://cloud-guide.meteor.com/apm-getting-started.html).
For those hosting outside of Galaxy the most popular solution is to go with [Monti APM](https://montiapm.com/) which shares
all the main functionality with Galaxy APM. You can also choose other APM for Node.js, but they will not show you Meteor
specific data that Galaxy APM and Monti APM specialize in. For this guide we will focus on showing how to work with Galaxy APM,
which is the same as with Monti APM, for simplicity.
Once you setup either of those APMs you will need to add a package to your Meteor app to start sending them data.
@@ -37,9 +37,9 @@ meteor add montiapm:agent
```
<h3 id="find-issues-apm">Finding issues in APM</h3>
APM will start with providing you with an overview of how your app is performing. You can then dive deep into details of
publications, methods, errors happening (both on client and server) and more. You will spend a lot of time in the detailed
tabs looking for methods and publications to improve and analyzing the impact of your actions. The process, for example for
APM will start with providing you with an overview of how your app is performing. You can then dive deep into details of
publications, methods, errors happening (both on client and server) and more. You will spend a lot of time in the detailed
tabs looking for methods and publications to improve and analyzing the impact of your actions. The process, for example for
optimizing methods, will look like this:
1. Go to the detailed view under the Methods tab.
@@ -52,14 +52,14 @@ Not every long-performing method has to be improved. Take a look at the followin
* methodX - mean response time 1 515 ms, throughput 100,05/min
* methodY - mean response time 34 000 ms, throughput 0,03/min
At first glance, the 34 seconds response time can catch your attention, and it may seem that the methodY
is more relevant to improvement. But dont ignore the fact that this method is being used only once in
At first glance, the 34 seconds response time can catch your attention, and it may seem that the methodY
is more relevant to improvement. But dont ignore the fact that this method is being used only once in
a few hours by the system administrators or scheduled cron action.
And now, lets take a look at the methodX. Its response time is evidently lower BUT compared to the frequency
And now, lets take a look at the methodX. Its response time is evidently lower BUT compared to the frequency
of use, it is still high, and without any doubt should be optimized first.
Its also absolutely vital to remember that you shouldn't optimize everything as it goes.
Its also absolutely vital to remember that you shouldn't optimize everything as it goes.
The key is to think strategically and match the most critical issues with your product priorities.
For more information about all the things you can find in Galaxy APM take a look at the Meteor APM section in [Galaxy Guide](https://galaxy-guide.meteor.com/apm-getting-started.html).
@@ -71,75 +71,75 @@ At the same this is the most resource intensive part of a Meteor application.
Under the hood WebSockets are being used with additional abilities provided by DDP.
<h3 id="publications-proper-use">Proper use of publications</h3>
Since publications can get resource intensive they should be reserved for usage that requires up to date, live data or
Since publications can get resource intensive they should be reserved for usage that requires up to date, live data or
that are changing frequently and you need the users to see that.
You will need to evaluate your app to figure out which situations these are. As a rule of thumb any data that are not
required to be live or are not changing frequently can be fetched once via other means and re-fetched as needed,
You will need to evaluate your app to figure out which situations these are. As a rule of thumb any data that are not
required to be live or are not changing frequently can be fetched once via other means and re-fetched as needed,
in most cases the re-fetching shouldn't be necessary.
But even before you proceed any further there are a few improvements that you can make here.
But even before you proceed any further there are a few improvements that you can make here.
First make sure that you only get the fields you need, limit the number of documents you send to the client to what you need
(aka always set the `limit` option) and ensure that you have set all your indexes.
<h4 id="publications-methods">Methods over publications</h3>
The first easiest replacement is to use Meteor methods instead of publications. In this case you can use the existing publication
and instead of returning a cursor you will call `.fetchAsync()` and return the actual data. The same performance improvements
The first easiest replacement is to use Meteor methods instead of publications. In this case you can use the existing publication
and instead of returning a cursor you will call `.fetchAsync()` and return the actual data. The same performance improvements
to get the method work faster apply here, but once called it sends the data and you don't have the overhead of a publication.
What is crucial here is to ensure that your choice of a front-end framework doesn't call the method every time, but only once
What is crucial here is to ensure that your choice of a front-end framework doesn't call the method every time, but only once
to load the data or when specifically needed (for example when the data gets updated due to user action or when the user requests it).
<h4 id="publications-replacements">Publication replacements</h4>
Using methods has its limitations and there are other tools that you might want to evaluate as a potential replacement.
[Grapher](https://github.com/cult-of-coders/grapher) is a favorite answer and allows you to easily blend with another
replacement which is [GraphQL](https://graphql.org/) and in particular [Apollo GraphQL](https://www.apollographql.com/),
[Grapher](https://github.com/cult-of-coders/grapher) is a favorite answer and allows you to easily blend with another
replacement which is [GraphQL](https://graphql.org/) and in particular [Apollo GraphQL](https://www.apollographql.com/),
which also has an integration [package](https://atmospherejs.com/meteor/apollo) with Meteor. Finally, you can also go back to using REST as well.
Do note, that you can mix all of these based on your needs.
<h3 id="low-observer-reuse">Low observer reuse</h3>
Observers are among the key components of Meteor. They take care of observing documents on MongoDB and they notify changes.
Observers are among the key components of Meteor. They take care of observing documents on MongoDB and they notify changes.
Creating them is an expensive operations, so you want to make sure that Meteor reuses them as much as possible.
> [Learn more about observers](https://galaxy-guide.meteor.com/apm-know-your-observers.html)
The key for observer reuse is to make sure that the queries requested are identical. This means that user given values
should be standardised and so should any dynamic input like time. Publications for users should check if user is signed in
The key for observer reuse is to make sure that the queries requested are identical. This means that user given values
should be standardised and so should any dynamic input like time. Publications for users should check if user is signed in
first before returning publication and if user is not signed in, then it should instead call `this.ready();`.
> [Learn more on improving observer reuse](https://galaxy-guide.meteor.com/apm-improve-cpu-and-network-usage)
<h3 id="redis-oplog">Redis Oplog</h3>
[Redis Oplog](https://atmospherejs.com/cultofcoders/redis-oplog) is a popular solution to Meteor's Oplog tailing
(which ensures the reactivity, but has some severe limitations that especially impact performance). Redis Oplog as name
suggests uses [redis](https://redis.io/) to track changes to data that you only need and cache them. This reduces load on
[Redis Oplog](https://atmospherejs.com/cultofcoders/redis-oplog) is a popular solution to Meteor's Oplog tailing
(which ensures the reactivity, but has some severe limitations that especially impact performance). Redis Oplog as name
suggests uses [redis](https://redis.io/) to track changes to data that you only need and cache them. This reduces load on
the server and database, allows you to track only the data that you want and only publish the changes you need.
<h2 id="methods">Methods</h2>
While methods are listed as one of the possible replacements for publications, they themselves can be made more performant,
after all it really depends on what you put inside them and APM will provide you with the necessary insight on which
While methods are listed as one of the possible replacements for publications, they themselves can be made more performant,
after all it really depends on what you put inside them and APM will provide you with the necessary insight on which
methods are the problem.
<h3 id="heavy-actions">Heavy actions</h3>
In general heavy tasks that take a lot of resources or take long and block the server for that time should be taken out
and instead be run in its own server that focuses just on running those heavy tasks. This can be another Meteor server
In general heavy tasks that take a lot of resources or take long and block the server for that time should be taken out
and instead be run in its own server that focuses just on running those heavy tasks. This can be another Meteor server
or even better something specifically optimized for that given task.
<h3 id="reoccurring-jobs">Reoccurring jobs</h3>
Reoccurring jobs are another prime candidate to be taken out into its own application. What this means is that you will have
an independent server that is going to be tasked with running the reoccurring jobs and the main application will only add to
Reoccurring jobs are another prime candidate to be taken out into its own application. What this means is that you will have
an independent server that is going to be tasked with running the reoccurring jobs and the main application will only add to
the list and be recipient of the results, most likely via database results.
<h3 id="rate-limiting">Rate limiting</h3>
Rate limit your methods to reduce effectiveness of DDOS attack and spare your server. This is also a good practice to
ensure that you don't accidentally DDOS your self. For example a user who clicks multiple time on a button that triggers
an expensive function. In this example you should also in general ensure that any button that triggers a server event
Rate limit your methods to reduce effectiveness of DDOS attack and spare your server. This is also a good practice to
ensure that you don't accidentally DDOS your self. For example a user who clicks multiple time on a button that triggers
an expensive function. In this example you should also in general ensure that any button that triggers a server event
should be disabled until there is a response from the server that the event has finished.
You can and should rate limit both methods and collections.
@@ -154,15 +154,15 @@ These are all applicable, and you should spend some time researching into them a
<h3 id="mongo-ip-whitelisting">IP whitelisting</h3>
If your MongoDB hosting provider allows it, you should make sure that you whitelist the IPs of your application servers.
If you don't then your database servers are likely to come under attack from hackers trying to brute force their way in.
If your MongoDB hosting provider allows it, you should make sure that you whitelist the IPs of your application servers.
If you don't then your database servers are likely to come under attack from hackers trying to brute force their way in.
Besides the security risk this also impacts performance as authentication is not a cheap operation and it will impact performance.
See [Galaxy guide](https://galaxy-guide.meteor.com/container-environment.html#network-outgoing) on IP whitelisting to get IPs for your Galaxy servers.
<h3 id="mongodb-indexes">Indexes</h3>
While single indexes on one field are helpful on simple query calls, you will most likely have more advance queries with
While single indexes on one field are helpful on simple query calls, you will most likely have more advance queries with
multiple variables. To cover those you will need to create compound indexes. For example:
```javascript
@@ -177,7 +177,7 @@ Statistics.createIndexAsync(
```
When creating indexes you should sort the variables in ESR (equity, sort, range) style.
Meaning, first you put variables that will be equal to something specific. Second you put variables that sort things,
and third variables that provide range for that query.
and third variables that provide range for that query.
Further you should order these variables in a way that the fields that filter the most should be first.
Make sure that all the indexes are used and remove unused indexes as leaving unused indexes will have negative impact
@@ -187,7 +187,7 @@ on performance as the database will have to still keep track on all the indexed
To optimize finds ensure that all queries have are indexed. Meaning that any `.find()` variables should be indexed as described above.
All your finds should have a limit on the return so that the database stops going through the data once it has reached
All your finds should have a limit on the return so that the database stops going through the data once it has reached
the limit, and you only return the limited number of results instead of the whole database.
Beware of queries with `n + 1` issue. For example in a database that has cars and car owners. You don't want to get cars,
@@ -202,14 +202,14 @@ If you still have issues make sure that you read data from secondaries.
<h3 id="beware-of-collection-hooks">Beware of collection hooks</h3>
While collection hooks can help in many cases beware of them and make sure that you understand how they work as they might
create additional queries that you might not know about. Make sure to review packages that use them so that they won't
While collection hooks can help in many cases beware of them and make sure that you understand how they work as they might
create additional queries that you might not know about. Make sure to review packages that use them so that they won't
create additional queries.
<h3 id="mongodb-caching">Caching</h3>
Once your user base increases you want to invest into query caching like using Redis, Redis Oplog and other.
For more complex queries or when you are retrieving data from multiple collections, then you want to use [aggregation](https://www.mongodb.com/docs/manual/aggregation/)
For more complex queries or when you are retrieving data from multiple collections, then you want to use [aggregation](https://www.mongodb.com/docs/manual/aggregation/)
and save their results.
<h2 id="scaling">Scaling</h2>
@@ -229,13 +229,13 @@ Galaxy has these as well. Learn more about [setting triggers for scaling on Gala
Setting this is vital, so that your application can keep on running when you have extra people come and then saves you money by scaling down when the containers are not in use.
When initially setting these pay a close attention to the performance of your app. you need to learn when is the right time to scale your app so it has enough time to spin up new containers before the existing one get overwhelmed by traffic and so on.
There are other points to pay attention to as well. For example if your app is used by corporation you might want to setup that on weekdays the minimum number of containers is going to increase just before the start of working hours and the then decrease the minimum to 1 for after hours and on weekends.
There are other points to pay attention to as well. For example if your app is used by corporation you might want to setup that on weekdays the minimum number of containers is going to increase just before the start of working hours and the then decrease the minimum to 1 for after hours and on weekends.
Usually when you are working on performance issues you will have higher numbers of containers as you optimize your app. It is therefore vital to revisit your scaling setting after each rounds of improvements to ensure that scaling triggers are properly optimized.
<h2 id="packages">Packages</h2>
During development, it is very tempting to add packages to solve issue or support some features.
This should be done carefully and each package should be wetted carefully if it is a good fit for the application.
Besides security and maintenance issues you also want to know which dependencies given package introduces and
During development, it is very tempting to add packages to solve issue or support some features.
This should be done carefully and each package should be wetted carefully if it is a good fit for the application.
Besides security and maintenance issues you also want to know which dependencies given package introduces and
as a whole what will be the impact on performance.

View File

@@ -11,9 +11,9 @@ Meteor supports many view layers.
The most popular are:
- [React](react.html): official [page](http://reactjs.org/)
- [Blaze](blaze.html): official [page](http://blazejs.org/)
- [Angular](http://www.angular-meteor.com): official [page](https://angular.io/)
- [Angular](angular.html): official [page](https://angular.io/)
- [Vue](vue.html): official [page](https://vuejs.org/)
- [Svelte](https://www.meteor.com/tutorials/svelte/creating-an-app): official [page](https://svelte.dev/)
- [Svelte](svelte.html): official [page](https://svelte.dev/)
If you are starting with web development we recommend that you use Blaze as it's very simple to learn.

View File

@@ -56,7 +56,7 @@ meteor
Building an application with Meteor?
* Deploy on Galaxy hosting: https://www.meteor.com/cloud
* Deploy on Galaxy hosting: https://galaxycloud.app/
* Announcement list: sign up at https://www.meteor.com/
* Discussion forums: https://forums.meteor.com/
* Join the Meteor community Slack by clicking this [invite link](https://join.slack.com/t/meteor-community/shared_invite/enQtODA0NTU2Nzk5MTA3LWY5NGMxMWRjZDgzYWMyMTEyYTQ3MTcwZmU2YjM5MTY3MjJkZjQ0NWRjOGZlYmIxZjFlYTA5Mjg4OTk3ODRiOTc).

View File

@@ -360,7 +360,7 @@ Or see the docs at:
Deploy and host your app with Cloud:
www.meteor.com/cloud
https://galaxycloud.app/
***************************************
You might need to open a new terminal window to have access to the meteor command, or run this in your terminal:

View File

@@ -1,17 +1,16 @@
{
"name": "meteor",
"version": "0.0.1",
"description": "Used to apply Prettier and ESLint manually",
"description": "Meteor's main repository, containing the Meteor tool, core packages, and documentation.",
"repository": {
"type": "git",
"url": "git+https://github.com/meteor/meteor.git"
},
"author": "Filipe Névola",
"license": "MIT",
"bugs": {
"url": "https://github.com/meteor/meteor/issues"
},
"homepage": "https://github.com/meteor/meteor#readme",
"homepage": "https://www.meteor.com/",
"devDependencies": {
"@babel/core": "^7.21.3",
"@babel/eslint-parser": "^7.21.3",
@@ -35,6 +34,9 @@
"prettier": "^2.8.8",
"typescript": "^5.4.5"
},
"scripts": {
"test:idle-bot": "node --test .github/scripts/__tests__/inactive-issues.test.js"
},
"jshintConfig": {
"esversion": 11
},

View File

@@ -205,7 +205,7 @@ export class AccountsCommon {
* @locus Anywhere
* @param {Object} options
* @param {Boolean} options.sendVerificationEmail New users with an email address will receive an address verification email.
* @param {Boolean} options.forbidClientAccountCreation Calls to [`createUser`](#accounts_createuser) from the client will be rejected. In addition, if you are using [accounts-ui](#accountsui), the "Create account" link will not be available.
* @param {Boolean} options.forbidClientAccountCreation Calls to [`createUser`](#accounts_createuser) from the client will be rejected. In addition, if you are using [accounts-ui](#accountsui), the "Create account" link will not be available. **Important**: This option must be set on both the client and server to take full effect. If only set on the server, account creation will be blocked but the UI will still show the "Create account" link.
* @param {String | Function} options.restrictCreationByEmailDomain If set to a string, only allows new users if the domain part of their email address matches the string. If set to a function, only allows new users if the function returns true. The function is passed the full email address of the proposed new user. Works with password-based sign-in and external services that expose email addresses (Google, Facebook, GitHub). All existing users still can log in after enabling this option. Example: `Accounts.config({ restrictCreationByEmailDomain: 'school.edu' })`.
* @param {Number} options.loginExpiration The number of milliseconds from when a user logs in until their token expires and they are logged out, for a more granular control. If `loginExpirationInDays` is set, it takes precedent.
* @param {Number} options.loginExpirationInDays The number of days from when a user logs in until their token expires and they are logged out. Defaults to 90. Set to `null` to disable login expiration.
@@ -226,6 +226,19 @@ export class AccountsCommon {
* @param {Number} options.loginTokenExpirationHours When using the package `accounts-2fa`, use this to set the amount of time a token sent is valid. As it's just a number, you can use, for example, 0.5 to make the token valid for just half hour. The default is 1 hour.
* @param {Number} options.tokenSequenceLength When using the package `accounts-2fa`, use this to the size of the token sequence generated. The default is 6.
* @param {'session' | 'local'} options.clientStorage By default login credentials are stored in local storage, setting this to true will switch to using session storage.
*
* @example
* // For UI-related options like forbidClientAccountCreation, call Accounts.config on both client and server
* // Create a shared configuration file (e.g., lib/accounts-config.js):
* import { Accounts } from 'meteor/accounts-base';
*
* Accounts.config({
* forbidClientAccountCreation: true,
* sendVerificationEmail: true,
* });
*
* // Then import this file in both client/main.js and server/main.js:
* // import '../lib/accounts-config.js';
*/
config(options) {
// We don't want users to accidentally only call Accounts.config on the

View File

@@ -730,7 +730,7 @@ if (Meteor.isServer) {
// create same user in two different collections - should pass
const email = "test-collection@testdomain.com"
const collection0 = new Mongo.Collection('test1');
const collection0 = new Mongo.Collection(`test1_${Random.id()}`);
Accounts.config({
collection: collection0,
@@ -738,7 +738,7 @@ if (Meteor.isServer) {
const uid0 = await Accounts.createUser({email})
await Meteor.users.removeAsync(uid0);
const collection1 = new Mongo.Collection('test2');
const collection1 = new Mongo.Collection(`test2_${Random.id()}`);
Accounts.config({
collection: collection1,
})
@@ -757,13 +757,13 @@ if (Meteor.isServer) {
const email = "test-collection@testdomain.com"
Accounts.config({
collection: 'collection0',
collection: `collection0_${Random.id()}`,
})
const uid0 = await Accounts.createUser({email})
await Meteor.users.removeAsync(uid0);
Accounts.config({
collection: 'collection1',
collection: `collection1_${Random.id()}`,
})
const uid1 = await Accounts.createUser({email})
await Meteor.users.removeAsync(uid1);

View File

@@ -14,6 +14,8 @@ const getTokenFromSecret = async ({ selector, secret: secretParam }) => {
return token;
};
Accounts.config({ ambiguousErrorMessages: false });
Meteor.methods({
async removeAccountsTestUser(username) {
await Meteor.users.removeAsync({ username });

View File

@@ -54,23 +54,37 @@ if (Meteor.isClient) (() => {
const removeSkipCaseInsensitiveChecksForTest = (value, test, expect) =>
Meteor.call('removeSkipCaseInsensitiveChecksForTest', value);
const createUserStep = function (test, expect) {
// Make logout steps awaitable so subsequent test steps don't race.
const logoutStep = async (test, expect) =>
new Promise(resolve => {
Meteor.logout(err => {
if (err) {
// keep original behavior: fail the test if logout errored
test.fail(err.message);
// still resolve so test runner can continue
return resolve();
}
test.equal(Meteor.user(), null);
resolve();
});
});
// Create user only after a confirmed logout to avoid races between
// tests that do login/logout operations.
const createUserStep = async function (test, expect) {
// Wait for the logout to complete synchronously.
await logoutStep(test, expect);
// Hack because Tinytest does not clean the database between tests/runs
this.randomSuffix = Random.id(10);
this.username = `AdaLovelace${ this.randomSuffix }`;
this.email = `Ada-intercept@lovelace.com${ this.randomSuffix }`;
this.password = 'password';
Accounts.createUser(
{ username: this.username, email: this.email, password: this.password },
loggedInAs(this.username, test, expect));
};
const logoutStep = (test, expect) =>
Meteor.logout(expect(error => {
if (error) {
test.fail(error.message);
}
test.equal(Meteor.user(), null);
}));
Accounts.createUser(
{ username: this.username, email: this.email, password: this.password },
loggedInAs(this.username, test, expect));
};
const loggedInAs = (someUsername, test, expect) => {
return expect(error => {
if (error) {
@@ -79,18 +93,7 @@ if (Meteor.isClient) (() => {
test.equal(Meteor.userId() && Meteor.user().username, someUsername);
});
};
const loggedInUserHasEmail = (someEmail, test, expect) => {
return expect(error => {
if (error) {
test.fail(error.message);
}
const user = Meteor.user();
test.isTrue(user && user.emails.reduce(
(prev, email) => prev || email.address === someEmail,
false
));
});
};
const expectError = (expectedError, test, expect) => expect(actualError => {
test.equal(actualError && actualError.error, expectedError.error);
test.equal(actualError && actualError.reason, expectedError.reason);
@@ -1300,6 +1303,7 @@ if (Meteor.isServer) (() => {
await Meteor.callAsync("resetPassword", resetPasswordToken, hashPasswordWithSha("new-password")),
/Token has invalid email address/
);
Accounts._options.ambiguousErrorMessages = true;
await test.throwsAsync(
async () =>
await Meteor.callAsync(
@@ -1380,6 +1384,7 @@ if (Meteor.isServer) (() => {
})
}
Accounts._options.ambiguousErrorMessages = true;
await test.throwsAsync(
async () => await Meteor.callAsync(
"login",
@@ -1669,6 +1674,7 @@ if (Meteor.isServer) (() => {
test.isTrue(userId1);
test.isTrue(userId2);
Accounts._options.ambiguousErrorMessages = false;
await test.throwsAsync(
async () => await Accounts.setUsername(userId2, usernameUpper),
/Username already exists/

View File

@@ -451,7 +451,8 @@ var runCommandOptions = {
...inspectOptions,
'no-release-check': { type: Boolean },
production: { type: Boolean },
'raw-logs': { type: Boolean },
'raw-logs': { type: Boolean, default: true },
timestamps: { type: Boolean, default: false }, // opposite of --raw-logs
settings: { type: String, short: "s" },
verbose: { type: Boolean, short: "v" },
// With --once, meteor does not re-run the project if it crashes
@@ -535,10 +536,7 @@ async function doRunCommand(options) {
);
}
if (options['raw-logs']) {
runLog.setRawLogs(true);
}
runLog.setRawLogs(options['raw-logs'] && !options.timestamps);
let webArchs = projectContext.platformList.getWebArchs();
if (! _.isEmpty(runTargets) ||
@@ -1127,7 +1125,7 @@ main.registerCommand({
"If you are new to Meteor, try some of the learning resources here:"
);
Console.info(
Console.url("https://www.meteor.com/tutorials"),
Console.url("https://docs.meteor.com/"),
Console.options({ indent: 2 })
);
@@ -1136,7 +1134,7 @@ main.registerCommand({
"When youre ready to deploy and host your new Meteor application, check out Cloud:"
);
Console.info(
Console.url("https://www.meteor.com/cloud"),
Console.url("https://galaxycloud.app/"),
Console.options({ indent: 2 })
);
@@ -2125,7 +2123,8 @@ testCommandOptions = {
// like progress bars and spinners are unimportant.
headless: { type: Boolean },
verbose: { type: Boolean, short: "v" },
'raw-logs': { type: Boolean },
'raw-logs': { type: Boolean, default: true },
timestamps: { type: Boolean, default: false }, // opposite of --raw-logs
// Undocumented. See #Once
once: { type: Boolean },
@@ -2176,7 +2175,7 @@ testCommandOptions = {
'extra-packages': { type: String },
'exclude-archs': { type: String },
// Same as TINYTEST_FILTER
filter: { type: String, short: 'f' },
}
@@ -2260,9 +2259,8 @@ async function doTestCommand(options) {
serverArchitectures.push(DEPLOY_ARCH);
}
if (options['raw-logs']) {
runLog.setRawLogs(true);
}
runLog.setRawLogs(options['raw-logs'] && !options.timestamps);
var includePackages = [];
if (options['extra-packages']) {

View File

@@ -90,7 +90,8 @@ Options:
Meteor app source code as by default the port is generated
using the id inside .meteor/.id file.
--production Simulate production mode. Minify and bundle CSS and JS files.
--raw-logs Run without parsing logs from stdout and stderr.
--raw-logs Run without parsing logs from stdout and stderr (default: true).
--timestamps Run with timestamps in logs, the same as passing `--raw-logs=false`.
--settings, -s Set optional data for Meteor.settings on the server.
--release Specify the release of Meteor to use.
--verbose Print all output from builds logs.
@@ -747,7 +748,9 @@ Options:
important when multiple Cordova apps are build from the same
Meteor app source code as by default the port is generated
using the id inside .meteor/.id file.
--raw-logs Run without parsing logs from stdout and stderr.
--raw-logs Run without parsing logs from stdout and stderr (default: true).
--timestamps Run with timestamps in logs, the same as passing `--raw-logs=false`.
--settings, -s Set optional data for Meteor.settings on the server
--ios, Run tests in an emulator or on a mobile device. All of

View File

@@ -403,7 +403,7 @@ selftest.define("run and SIGKILL parent process", ["yet-unsolved-windows-failure
await s.createApp("myapp", "app-prints-pid");
s.cd("myapp");
run = s.run();
run = s.run("run", "--timestamps");
run.waitSecs(30);
var match = await run.match(/My pid is (\d+)/);
var childPid;
@@ -434,7 +434,8 @@ selftest.define("run and SIGKILL parent process", ["yet-unsolved-windows-failure
// Test that passing a bad pid in $METEOR_PARENT_PID logs an error and exits
// immediately.
s.set("METEOR_BAD_PARENT_PID_FOR_TEST", "t");
run = s.run();
run = s.run("run", "--timestamps");
run.waitSecs(120);
await run.match("must be a valid process ID");
await run.match("Your application is crashing");

View File

@@ -40,6 +40,18 @@ export default defineConfig({
text: "Meteor + Vue + vue-meteor-tracker",
link: "/tutorials/vue/meteorjs3-vue3-vue-meteor-tracker",
},
{
text: "Meteor.js 3 + Solid",
link: "/tutorials/solid/index",
},
{
text: "Meteor.js 3 + Blaze",
link: "/tutorials/blaze/index",
},
{
text: "Meteor.js 3 + Svelte",
link: "/tutorials/svelte/index",
},
{
link: "/tutorials/application-structure/index",
text: "Application structure",
@@ -114,7 +126,7 @@ export default defineConfig({
],
},
{ text: "API", link: "/api/" },
{ text: "Galaxy Cloud", link: "https://www.meteor.com/cloud" },
{ text: "Galaxy Cloud", link: "https://galaxycloud.app" },
{
text: metadata.currentVersion,
items: metadata.versions.reverse().map((v) => {
@@ -140,15 +152,21 @@ export default defineConfig({
{
text: "What is Meteor?",
link: "/about/what-is#introduction",
},
{
text: "Meteor resources",
link: "/about/what-is#learning-more",
items:[
{
text: "Meteor resources",
link: "/about/what-is#learning-more",
},
],
},
{
text: "Roadmap",
link: "/about/roadmap",
},
{
text: "Contributing",
link: "/about/contributing",
}
],
collapsed: true,
},
@@ -472,6 +490,18 @@ export default defineConfig({
link: "/tutorials/vue/meteorjs3-vue3-vue-meteor-tracker",
text: "Meteor + Vue + vue-meteor-tracker",
},
{
text: "Meteor.js 3 + Solid",
link: "/tutorials/solid/index",
},
{
text: "Meteor.js 3 + Blaze",
link: "/tutorials/blaze/index",
},
{
text: "Meteor.js 3 + Svelte",
link: "/tutorials/svelte/index",
},
{
link: "/tutorials/application-structure/index",
text: "Application structure",

View File

View File

@@ -0,0 +1,40 @@
## Contributing to Meteor
Ongoing Meteor development takes place in the open [on GitHub](https://github.com/meteor/meteor). We encourage pull requests and issues to discuss problems with any changes that could be made to the content. The contribution guidelines are available in the [Meteor GitHub repository](https://github.com/meteor/meteor/blob/devel/CONTRIBUTING.md).
A great start to understand how to contribute to Meteor Core is this video from Meteor Impact 2025:
<iframe width="560" height="315" src="https://www.youtube.com/embed/-EZtClGGmP8?si=LcuhDNrgmcLaNIbH" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Contributing to this documentation
We welcome contributions to the documentation!
Since documentation is always evolving, your help is really valuable to ensure content is accurate and up-to-date.
### How to Contribute
#### Identify elements that need improvement
Are you new here? Please check our [documentation issues](https://github.com/meteor/meteor/issues?q=is%3Aissue%20state%3Aopen%20label%3AProject%3ADocs).
If in doubt about the best way to implement something, please create additional conversation on the issue.
Issues are not assigned, you dont need to wait for approval before contributing. Jump right in and open a PR — this increases your chances of getting your work merged, since issues can be claimed fast.
#### Do the changes and share them
Documentation live in the `v3-docs/docs` directory of the [Meteor GitHub repository](https://github.com/meteor/meteor/tree/devel/v3-docs/docs)
For small changes, such as fixing typos or formatting, you can simply click the "Edit this page on GitHub" button in the footer to edit the file and submit a PR.
For larger changes, you need to fork meteor repo and start your work from the `devel` branch.
You must test your contribution locally before submitting a pull request. To do so, here are the steps:
1. `cd v3-docs/docs && npm run docs:dev` will run the docs locally at [http://localhost:5173/](http://localhost:5173/)
2. Make your changes and verify them in the browser.
3. run `npm run docs:build` to ensure the build works correctly.
4. Push your work and submit a documented pull request to the `devel` branch.
If you add a new page to the documentation, please make sure the configuration creates a link to access it (see [.vitepress/config.mts](https://github.com/meteor/meteor/blob/devel/v3-docs/docs/.vitepress/config.mts)).

View File

@@ -57,7 +57,7 @@ App.launchScreens({
});
// Set PhoneGap/Cordova preferences.
App.setPreference('BackgroundColor', '0xff0000ff');
App.setPreference('BackgroundColor', '#000000ff');
App.setPreference('HideKeyboardFormAccessoryBar', true);
App.setPreference('Orientation', 'default');
App.setPreference('Orientation', 'all', 'ios');

View File

@@ -30,7 +30,7 @@ Meteor.startup(async () => {
if ((await LinksCollection.find().countAsync()) === 0) {
await LinksCollection.insertAsync({
title: "Do the Tutorial",
url: "https://www.meteor.com/tutorials/react/creating-an-app",
url: "https://docs.meteor.com/tutorials/react",
});
}
});
@@ -148,10 +148,7 @@ import { Meteor } from "meteor/meteor";
function Component() {
const addLink = () =>
Meteor.callAsync(
"addLink",
"https://www.meteor.com/tutorials/react/creating-an-app"
);
Meteor.callAsync("addLink", "https://docs.meteor.com/tutorials/react/");
return (
<div>
@@ -398,7 +395,6 @@ even if the method's writes are not available yet, you can specify an
Use `Meteor.call` only to call methods that do not have a stub, or have a sync stub. If you want to call methods with an async stub, `Meteor.callAsync` can be used with any method.
:::
<ApiBox name="Meteor.callAsync" />
`Meteor.callAsync` is just like `Meteor.call`, except that it'll return a promise that you need to solve to get the server result. Along with the promise returned by `callAsync`, you can also handle `stubPromise` and `serverPromise` for managing client-side simulation and server response.
@@ -409,64 +405,63 @@ The following sections guide you in understanding these promises and how to mana
```javascript
try {
await Meteor.callAsync('greetUser', 'John');
// 🟢 Server ended with success
} catch(e) {
console.error("Error:", error.reason); // 🔴 Server ended with error
await Meteor.callAsync("greetUser", "John");
// 🟢 Server ended with success
} catch (e) {
console.error("Error:", error.reason); // 🔴 Server ended with error
}
Greetings.findOne({ name: 'John' }); // 🗑️ Data is NOT available
Greetings.findOne({ name: "John" }); // 🗑️ Data is NOT available
```
#### stubPromise
```javascript
await Meteor.callAsync('greetUser', 'John').stubPromise;
await Meteor.callAsync("greetUser", "John").stubPromise;
// 🔵 Client simulation
Greetings.findOne({ name: 'John' }); // 🧾 Data is available (Optimistic-UI)
Greetings.findOne({ name: "John" }); // 🧾 Data is available (Optimistic-UI)
```
#### stubPromise and serverPromise
```javascript
const { stubPromise, serverPromise } = Meteor.callAsync('greetUser', 'John');
const { stubPromise, serverPromise } = Meteor.callAsync("greetUser", "John");
await stubPromise;
// 🔵 Client simulation
Greetings.findOne({ name: 'John' }); // 🧾 Data is available (Optimistic-UI)
Greetings.findOne({ name: "John" }); // 🧾 Data is available (Optimistic-UI)
try {
await serverPromise;
// 🟢 Server ended with success
} catch(e) {
} catch (e) {
console.error("Error:", error.reason); // 🔴 Server ended with error
}
Greetings.findOne({ name: 'John' }); // 🗑️ Data is NOT available
Greetings.findOne({ name: "John" }); // 🗑️ Data is NOT available
```
#### Meteor 2.x contrast
For those familiar with legacy Meteor 2.x, the handling of client simulation and server response was managed using fibers, as explained in the following section. This comparison illustrates how async inclusion with standard promises has transformed the way Meteor operates in modern versions.
``` javascript
Meteor.call('greetUser', 'John', function(error, result) {
```javascript
Meteor.call("greetUser", "John", function (error, result) {
if (error) {
console.error("Error:", error.reason); // 🔴 Server ended with error
} else {
console.log("Result:", result); // 🟢 Server ended with success
}
Greetings.findOne({ name: 'John' }); // 🗑️ Data is NOT available
Greetings.findOne({ name: "John" }); // 🗑️ Data is NOT available
});
// 🔵 Client simulation
Greetings.findOne({ name: 'John' }); // 🧾 Data is available (Optimistic-UI)
Greetings.findOne({ name: "John" }); // 🧾 Data is available (Optimistic-UI)
```
<ApiBox name="Meteor.apply" />
`Meteor.apply` is just like `Meteor.call`, except that the method arguments are
@@ -504,8 +499,6 @@ different collections. We hope to lift this restriction in a future release.
</ApiBox>
```js
import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";

View File

@@ -53,7 +53,8 @@ This is the default command. Simply running `meteor` is the same as `meteor run`
| `--mobile-server <url>` | Location where mobile builds connect (defaults to local IP and port). Can include URL scheme (e.g., https://example.com:443) |
| `--cordova-server-port <port>` | Local port where Cordova will serve content |
| `--production` | Simulate production mode. Minify and bundle CSS and JS files |
| `--raw-logs` | Run without parsing logs from stdout and stderr |
| `--raw-logs` | Run without parsing logs from stdout and stderr (default: true) |
| `--timestamps` | Run with timestamps in logs, the same as passing `--raw-logs=false`. |
| `--settings`, `-s <file>` | Set optional data for Meteor.settings on the server |
| `--release <version>` | Specify the release of Meteor to use |
| `--verbose` | Print all output from builds logs |
@@ -247,10 +248,10 @@ If you run `meteor create` without arguments, Meteor will launch an interactive
Typescript # To create an app using TypeScript and React
Vue # To create a basic Vue3-based app
Svelte # To create a basic Svelte app
Tailwind # To create an app using React and Tailwind
Chakra-ui # To create an app Chakra UI and React
Solid # To create a basic Solid app
Apollo # To create a basic Apollo + React app
Tailwind # To create an app using React and Tailwind
Chakra-ui # To create an app Chakra UI and React
Solid # To create a basic Solid app
Apollo # To create a basic Apollo + React app
Bare # To create an empty app
```
:::
@@ -359,7 +360,7 @@ To learn more about the recommended file structure for Meteor apps, check the [M
## meteor generate {meteorgenerate}
``meteor generate`` is a command to generate boilerplate for your current project. `meteor generate` receives a name as a parameter, and generates files containing code to create a [Collection](https://docs.meteor.com/api/collections.html) with that name, [Methods](https://docs.meteor.com/api/meteor.html#methods) to perform basic CRUD operations on that Collection, and a [Subscription](https://docs.meteor.com/api/meteor.html#Meteor-publish) to read its data with reactivity from the client.
``meteor generate`` is a command to generate boilerplate for your current project. `meteor generate` receives a name as a parameter, and generates files containing code to create a [Collection](https://docs.meteor.com/api/collections.html) with that name, [Methods](https://docs.meteor.com/api/meteor.html#methods) to perform basic CRUD operations on that Collection, and a [Subscription](https://docs.meteor.com/api/meteor.html#Meteor-publish) to read its data with reactivity from the client.
If you run ``meteor generate`` without arguments, it will ask you for a name, and name the auto-generated Collection accordingly. It will also ask if you do want Methods for your API and Publications to be generated as well.

View File

@@ -44,6 +44,9 @@ const sourceCode = `https://github.com/meteor/meteor/blob/devel/packages/${props
</script>
<template>
<div v-if="localArr.length > 0">
<header>
@@ -81,8 +84,9 @@ const sourceCode = `https://github.com/meteor/meteor/blob/devel/packages/${props
</tr>
</tbody>
</table>
<Collapse v-if="hasOptions(props) && props.options && props.options?.length > 0" :when="isOptionsTableOpen"
class="options-table">
<Collapse :when ="isOptionsTableOpen" class ="options-table" v-show="hasOptions(props) && props.options && props.options?.length>0">
<h4>Options:</h4>
<table>
<thead>
@@ -103,6 +107,7 @@ const sourceCode = `https://github.com/meteor/meteor/blob/devel/packages/${props
</tbody>
</table>
</Collapse>
</div>
</template>

View File

@@ -0,0 +1,190 @@
## 1: Creating the app
### 1.1: Install Meteor
First, we need to install Meteor by following this [installation guide](https://docs.meteor.com/about/install.html).
### 1.2: Create Meteor Project
The easiest way to setup Meteor with Blaze is by using the command `meteor create` with the option `--blaze` and your project name:
```shell
meteor create --blaze simple-todos-blaze
```
Meteor will create all the necessary files for you.
The files located in the `client` directory are setting up your client side (web), you can see for example `client/main.html` where Meteor is rendering your App main component into the HTML.
Also, check the `server` directory where Meteor is setting up the server side (Node.js), you can see the `server/main.js` which would be a good place to initialize your MongoDB database with some data. You don't need to install MongoDB as Meteor provides an embedded version of it ready for you to use.
You can now run your Meteor app using:
```shell
meteor
```
Don't worry, Meteor will keep your app in sync with all your changes from now on.
Take a quick look at all the files created by Meteor, you don't need to understand them now but it's good to know where they are.
Your Blaze code will be located inside the `imports/ui` directory, and the `App.html` and `App.js` files will be the root component of your Blaze To-do app. We haven't made those yet but will soon.
### 1.3: Create Task Component
To start working on our todo list app, lets replace the code of the default starter app with the code below. From there, well talk about what it does.
First, lets remove the body from our HTML entry-point (leaving just the `<head>` tag):
::: code-group
```html [client/main.html]
<head>
<title>Simple todo</title>
</head>
```
:::
Create a new directory named `imports` inside the `simple-todos-blaze` folder. In the `imports` folder, create another directory with the name `ui` and add an `App.html` file inside of it with the content below:
::: code-group
```html [imports/ui/App.html]
<body>
{{> mainContainer }}
</body>
<template name="mainContainer">
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</template>
<template name="task">
<li>{{text}}</li>
</template>
```
:::
We just created two templates, the `mainContainer`, which will be rendered in the body of our app, and it will show a header and a list of tasks that will render each item using the `task` template. Now, we need some data to present sample tasks on this page.
### 1.4: Create Sample Tasks
Create a new file called `App.js` in your `ui` folder.
Inside your entry-point `main.js` file, remove all the previous content and just add the code below to import the new file `imports/ui/App.js`:
::: code-group
```js [client/main.js]
import '../imports/ui/App.js';
```
:::
As you are not connecting to your server and database yet, lets define some sample data, which we will use shortly to render a list of tasks. Add the code below to the `App.js` file:
::: code-group
```js [imports/ui/App.js]
import { Template } from 'meteor/templating';
import './App.html';
Template.mainContainer.helpers({
tasks: [
{ text: 'This is task 1' },
{ text: 'This is task 2' },
{ text: 'This is task 3' },
],
});
```
:::
Adding a helper to the `mainContainer` template, you are able to define the array of tasks. When the app starts, the client-side entry-point will import the `App.js` file, which will also import the `App.html` template we created in the previous step.
At this point meteor should be running on port 3000 so you can visit the running app and see your list with three tasks displayed at [http://localhost:3000/](http://localhost:3000/) - but if meteor is not running, go to your terminal and move to the top directory of your project and type `meteor` then press return to launch the app.
All right! Lets find out what all these bits of code are doing!
### 1.5: Rendering Data
<img width="688px" src="/tutorials/blaze/assets/mermaid-diagram-blaze-rendering.png"/>
Meteor parses HTML files and identifies three top-level tags: `<head>`, `<body>`, and `<template>`.
Everything inside any `<head>` tags is added to the head section of the HTML sent to the client, and everything inside `<body>` tags is added to the body section, just like in a regular HTML file.
Everything inside `<template>` tags is compiled into Meteor templates, which can be included inside HTML with <span v-pre>{{> templateName}}</span> or referenced in your JavaScript with `Template.templateName`.
Also, the `body` section can be referenced in your JavaScript with `Template.body`. Think of it as a special “parent” template, that can include the other child templates.
All of the code in your HTML files will be compiled with [Meteors Spacebars compiler](http://blazejs.org/api/spacebars.html). Spacebars uses statements surrounded by double curly braces such as <span v-pre>{{#each}}</span> and <span v-pre>{{#if}}</span> to let you add logic and data to your views.
You can pass data into templates from your JavaScript code by defining helpers. In the code above, we defined a helper called `tasks` on `Template.mainContainer` that returns an array. Inside the template tag of the HTML, we can use <span v-pre>{{#each tasks}}</span> to iterate over the array and insert a task template for each value. Inside the #each block, we can display the text property of each array item using <span v-pre>{{text}}</span>.
### 1.6: Mobile Look
Lets see how your app is looking on mobile. You can simulate a mobile environment by `right clicking` your app in the browser (we are assuming you are using Google Chrome, as it is the most popular browser) and then `inspect`, this will open a new window inside your browser called `Dev Tools`. In the `Dev Tools` you have a small icon showing a Mobile device and a Tablet:
<img width="500px" src="/tutorials/blaze/assets/step01-dev-tools-mobile-toggle.png"/>
Click on it and then select the phone that you want to simulate and in the top nav bar.
> You can also check your app in your personal cellphone. To do so, connect to your App using your local IP in the navigation browser of your mobile browser.
>
> This command should print your local IP for you on Unix systems
> `ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'`
>
> On Microsoft Windows try this in a command prompt
> `ipconfig | findstr "IPv4 Address"`
You should see the following:
<img width="200px" src="/tutorials/blaze/assets/step01-mobile-without-meta-tags.png"/>
As you can see, everything is small, as we are not adjusting the view port for mobile devices. You can fix this and other similar issues by adding these lines to your `client/main.html` file, inside the `head` tag, after the `title`.
::: code-group
```html [client/main.html]
...
<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"/>
...
```
:::
Now your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step01-mobile-with-meta-tags.png"/>
### 1.7: Hot Module Replacement
By default, when using Blaze with Meteor, a package called [hot-module-replacement](https://docs.meteor.com/packages/hot-module-replacement) is already added for you. This package updates the javascript modules in a running app that were modified during a rebuild. Reduces the feedback cycle while developing, so you can view and test changes quicker (it even updates the app before the build has finished). You are also not going to lose the state, your app code will be updated, and your state will be the same.
> You can read more about packages [here](https://docs.meteor.com/packages/).
You should also add the package [dev-error-overlay](https://atmospherejs.com/meteor/dev-error-overlay) at this point, so you can see the errors in your web browser.
```shell
meteor add dev-error-overlay
```
You can try to make some mistakes and then you are going to see the errors in the browser and not only in the console.
In the next step we are going to work with our MongoDB database to be able to store our tasks.

View File

@@ -0,0 +1,156 @@
## 2: Collections
Meteor already sets up MongoDB for you. In order to use our database, we need to create a _collection_, which is where we will store our _documents_, in our case our `tasks`.
> You can read more about collections [here](https://v3-docs.meteor.com/api/collections.html).
In this step we will implement all the necessary code to have a basic collection for our tasks up and running.
### 2.1: Create Tasks Collection {#create-tasks-collection}
Create a new directory in `imports/api` if it doesn't exist already. We can create a new collection to store our tasks by creating a new file at `imports/api/TasksCollection.js` which instantiates a new Mongo collection and exports it.
::: code-group
```js [imports/api/TasksCollection.js]
import { Mongo } from "meteor/mongo";
export const TasksCollection = new Mongo.Collection("tasks");
```
:::
Notice that we stored the file in the `imports/api` directory, which is a place to store API-related code, like publications and methods. You can name this folder as you want, this is just a choice.
> You can read more about app structure and imports/exports [here](http://guide.meteor.com/structure.html).
### 2.2: Initialize Tasks Collection {#initialize-tasks-collection}
For our collection to work, you need to import it in the server so it sets some plumbing up.
You can either use `import "/imports/api/TasksCollection"` or `import { TasksCollection } from "/imports/api/TasksCollection"` if you are going to use on the same file, but make sure it is imported.
Now it is easy to check if there is data or not in our collection, otherwise, we can insert some sample data easily as well.
You don't need to keep the old content of `server/main.js`.
::: code-group
```js [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
const insertTask = (taskText) =>
TasksCollection.insertAsync({ text: taskText });
Meteor.startup(async () => {
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach(insertTask);
}
});
```
:::
So you are importing the `TasksCollection` and adding a few tasks to it iterating over an array of strings and for each string calling a function to insert this string as our `text` field in our `task` document.
### 2.3: Render Tasks Collection {#render-tasks-collection}
Now comes the fun part, you will render the tasks with Blaze. That will be pretty simple.
In your `App.js` file, import the `TasksCollection` file and, instead of returning a static array, return the tasks saved in the database:
::: code-group
```javascript [imports/ui/App.js]
import { Template } from 'meteor/templating';
import { TasksCollection } from "../api/TasksCollection";
import './App.html';
Template.mainContainer.helpers({
tasks() {
return TasksCollection.find({});
},
});
```
:::
But wait! Something is missing. If you run your app now, you'll see that you don't render any tasks.
That's because we need to publish our data to the client.
> For more information on Publications/Subscriptions, please check our [docs](https://v3-docs.meteor.com/api/meteor.html#pubsub).
Meteor doesn't need REST calls. It instead relies on synchronizing the MongoDB on the server with a MiniMongoDB on the client. It does this by first publishing collections on the server and then subscribing to them on the client.
First, create a publication for our tasks:
::: code-group
```javascript [imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
return TasksCollection.find();
});
```
:::
Now, we need to import this file in our server:
::: code-group
```js [server/main.js]
...
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksPublications"; // [!code highlight]
const insertTask = taskText => TasksCollection.insertAsync({ text: taskText });
...
```
:::
The only thing left is subscribe to this publication:
::: code-group
```javascript [imports/ui/App.js]
...
Template.mainContainer.onCreated(function mainContainerOnCreated() {
Meteor.subscribe('tasks');
});
...
```
:::
See how your app should look like now:
<img width="200px" src="/tutorials/blaze/assets/collections-tasks-list.png"/>
You can change your data on MongoDB in the server and your app will react and re-render for you.
You can connect to your MongoDB running `meteor mongo` in the terminal from your app folder or using a Mongo UI client, like [NoSQLBooster](https://nosqlbooster.com/downloads). Your embedded MongoDB is running in port `3001`.
See how to connect:
<img width="500px" src="/tutorials/blaze/assets/collections-connect-db.png"/>
See your database:
<img width="500px" src="/tutorials/blaze/assets/collections-see-database.png"/>
You can double-click your collection to see the documents stored on it:
<img width="500px" src="/tutorials/blaze/assets/collections-documents.png"/>
In the next step, we are going to create tasks using a form.

View File

@@ -0,0 +1,205 @@
## 3: Forms and Events
All apps need to allow the user to perform some sort of interaction with the data that is stored. In our case, the first type of interaction is to insert new tasks. Without it, our To-Do app wouldn't be very helpful.
One of the main ways in which a user can insert or edit data on a website is through forms. In most cases, it is a good idea to use the `<form>` tag since it gives semantic meaning to the elements inside it.
### 3.1: Create Task Form
First, we need to create a simple form component to encapsulate our logic.
Create a new template named `form` inside the `App.html` file, and inside of the new template, well add an input field and a button:
::: code-group
```html [imports/ui/App.html]
...
<template name="form">
<form class="task-form">
<input type="text" name="text" placeholder="Type to add new tasks" />
<button type="submit">Add Task</button>
</form>
</template>
```
:::
### 3.2: Update the mainContainer template element
Then we can simply add this to our `mainContainer` template above your list of tasks:
::: code-group
```html [imports/ui/App.html]
...
<template name="mainContainer">
<div class="container">
<header>
<h1>Todo List</h1>
</header>
{{> form }}
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</template>
...
```
:::
We are rendering the `form` template that we created in the previous step, and we are iterating over each of the `tasks` and rendering them using the `task` template.
### 3.3: Update the Stylesheet
You also can style it as you wish. For now, we only need some margin at the top so the form doesn't seem off the mark. Add the CSS class `.task-form`, this needs to be the same name in your `class` attribute in the form component.
::: code-group
```css [client/main.css]
.task-form {
margin-top: 1rem;
}
```
:::
### 3.4: Add Submit Handler
Now let's create a function to handle the form submit and insert a new task into the database. To do it, we will need to implement a Meteor Method.
Methods are essentially RPC calls to the server that let you perform operations on the server side securely. You can read more about Meteor Methods [here](https://guide.meteor.com/methods.html).
To create your methods, you can create a file called `TasksMethods.js`.
::: code-group
```javascript [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
"tasks.insert"(doc) {
return TasksCollection.insertAsync(doc);
},
});
```
:::
Remember to import your method on the `main.js` server file, delete the `insertTask` function, and invoke the new meteor method inside the `forEach` block.
::: code-group
```javascript [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
import "../imports/api/TasksPublications";
import "../imports/api/TasksMethods"; // [!code highlight]
Meteor.startup(async () => {
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", { // [!code highlight]
text: taskName, // [!code highlight]
createdAt: new Date(), // [!code highlight]
});
});
}
});
```
:::
Inside the `forEach` function, we are adding a task to the `tasks` collection by calling `Meteor.callAsync()`. The first argument is the name of the method we want to call, and the second argument is the text of the task.
Also, insert a date `createdAt` in your `task` document so you know when each task was created.
Now we need to import `TasksMethods.js` and add a listener to the `submit` event on the form:
::: code-group
```js [imports/ui/App.js]
import { Template } from 'meteor/templating';
import { TasksCollection } from "../api/TasksCollection";
import '/imports/api/TasksMethods.js'; // this import in this client UI allows for optimistic execution
import './App.html';
Template.mainContainer.onCreated(function mainContainerOnCreated() {
Meteor.subscribe('tasks');
});
Template.mainContainer.helpers({
tasks() {
return TasksCollection.find({});
},
});
Template.form.events({
"submit .task-form"(event) {
// Prevent default browser form submit
event.preventDefault();
// Get value from form element
const target = event.target;
const text = target.text.value;
// Insert a task into the collection
Meteor.callAsync("tasks.insert", {
text,
createdAt: new Date(), // current time
});
// Clear form
target.text.value = '';
}
});
```
:::
Event listeners are added to templates in much the same way as helpers are: by calling `Template.templateName.events(...)` with a dictionary. The keys describe the event to listen for, and the values are event handlers called when the event happens.
In our case above, we listen to the `submit` event on any element that matches the CSS selector `.task-form`. When this event is triggered by the user pressing enter inside the input field or the submit button, our event handler function is called.
The event handler gets an argument called `event` that has some information about the triggered event. In this case, `event.target` is our form element, and we can get the value of our input with `event.target.text.value`. You can see all the other properties of the event object by adding a `console.log(event)` and inspecting the object in your browser console.
Just like on the server side, we are adding a task to the `tasks` collection by calling `Meteor.callAsync("tasks.insert")`. It will first execute on the client optimistically using minimongo while simultaneously making the remote procedure call on the server. If the server call fails, minimongo will rollback the change on the client. This gives the speediest user experience. It's a bit like [rollback netcode](https://glossary.infil.net/?t=Rollback%20Netcode) in fighting video games.
Finally, in the last line of the event handler, we need to clear the input to prepare for another new task.
### 3.5: Show Newest Tasks First
Now you just need to make a change that will make users happy: we need to show the newest tasks first. We can accomplish this quite quickly by sorting our [Mongo](https://guide.meteor.com/collections.html#mongo-collections) query.
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.helpers({
tasks() {
return TasksCollection.find({}, { sort: { createdAt: -1 } });
},
});
...
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step03-form-new-task.png"/>
<img width="200px" src="/tutorials/blaze/assets/step03-new-task-on-list.png"/>
In the next step, we are going to update your tasks state and provide a way for users to remove tasks.

View File

@@ -0,0 +1,170 @@
## 4: Update and Remove
Up until now, you have only inserted documents into our collection. Let's take a look at how you can update and remove them by interacting with the user interface.
### 4.1: Add Checkbox
First, you need to add a `checkbox` element to your `Task` component.
Next, lets create a new file for our `task` template in `imports/ui/Task.html`, so we can start to separate the logic in our app.
::: code-group
```html [imports/ui/Task.html]
<template name="task">
<li>
<label>
<input type="checkbox" checked="{{isChecked}}" class="toggle-checked" />
<span>{{text}}</span>
</label>
</li>
</template>
```
:::
Dont forget to remove the template named `task` in `imports/ui/App.html`.
You must also add the following import:
::: code-group
```js [imports/ui/App.js]
...
import './Task';
...
```
:::
### 4.2: Toggle Checkbox
Now you can update your task document by toggling its `isChecked` field.
First, create a new method called `tasks.toggleChecked` to update the `isChecked` property.
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
..
"tasks.toggleChecked"({ _id, isChecked }) {
return TasksCollection.updateAsync(_id, {
$set: { isChecked: !isChecked },
});
},
});
```
:::
Create a new file called `Task.js` so we can have our handlers to the `task` template:
::: code-group
```js [imports/ui/Task.js]
import { Template } from 'meteor/templating';
import { TasksCollection } from "../api/TasksCollection";
import '/imports/api/TasksMethods.js'; // this import in this client UI allows for optimistic execution
import './Task.html';
Template.task.events({
'click .toggle-checked'() {
// Set the checked property to the opposite of its current value
let taskID = this._id;
let checkedValue = Boolean(this.isChecked);
Meteor.callAsync("tasks.toggleChecked", { _id: taskID, isChecked: checkedValue });
},
});
```
:::
Toggling checkboxes should now persist in the DB even if you refresh the web browser.
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step04-checkbox.png"/>
If your computer is fast enough, it's possible that when it sets up the default tasks a few will have the same date. That will cause them to non-deterministically "jump around" in the UI as you toggle checkboxes and the UI reactively updates. To make it stable, you can add a secondary sort on the `_id` of the task:
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.helpers({
tasks() {
return TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } });
},
...
```
:::
### 4.3: Remove tasks
You can remove tasks with just a few lines of code.
First, add a button after text `label` in your `Task` component.
::: code-group
```html [imports/ui/Task.html]
<template name="task">
<li>
<label>
<input type="checkbox" checked="{{isChecked}}" class="toggle-checked" />
<span>{{text}}</span>
</label>
<button class="delete">&times;</button>
</li>
...
```
:::
Next you need to have a function to delete the task. For that, let's create a new method called `tasks.delete`:
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
..
"tasks.delete"({ _id }) {
return TasksCollection.removeAsync(_id);
},
});
```
:::
Now add the removal logic in the `Task.js`. It will just be a new event to the `task` template that is activated when the user clicks on a delete button (i.e. any button with the class `delete`):
::: code-group
```javascript [imports/ui/Task.js]
...
Template.task.events({
...,
'click .delete'() {
let taskID = this._id;
Meteor.callAsync("tasks.delete", { _id: taskID });
},
});
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step04-delete-button.png"/>
### 4.4: Getting data in event handlers
In a collection, every inserted document has a unique `_id` field that can refer to that specific document. Inside the event handlers, `this` refers to an individual task object. We can get the `_id` of the current task with `this._id` and any other field available on the client-side. Once we have the `_id`, we can use, update, and remove the relevant task. Thats how our code will update or remove a task.
In the next step, we are going to improve the look of your app using CSS with Flexbox.

View File

@@ -0,0 +1,188 @@
## 5: Styles
### 5.1: CSS
Our user interface up until this point has looked quite ugly. Let's add some basic styling which will serve as the foundation for a more professional looking app.
Replace the content of our `client/main.css` file with the one below, the idea is to have an app bar at the top, and a scrollable content including:
- form to add new tasks;
- list of tasks.
::: code-group
```css [client/main.css]
body {
font-family: sans-serif;
background-color: #315481;
background-image: linear-gradient(to bottom, #315481, #918e82 100%);
background-attachment: fixed;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
font-size: 14px;
}
button {
font-weight: bold;
font-size: 1em;
border: none;
color: white;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
padding: 5px;
cursor: pointer;
}
button:focus {
outline: 0;
}
.app {
display: flex;
flex-direction: column;
height: 100vh;
}
.app-header {
flex-grow: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.main {
display: flex;
flex-direction: column;
flex-grow: 1;
overflow: auto;
background: white;
}
.main::-webkit-scrollbar {
width: 0;
height: 0;
background: inherit;
}
header {
background: #d2edf4;
background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
padding: 20px 15px 15px 15px;
position: relative;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
}
.app-bar {
display: flex;
justify-content: space-between;
}
.app-bar h1 {
font-size: 1.5em;
margin: 0;
display: inline-block;
margin-right: 1em;
}
.task-form {
display: flex;
margin: 16px;
}
.task-form > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
}
.task-form > input:focus {
outline: 0;
}
.task-form > button {
min-width: 100px;
height: 95%;
background-color: #315481;
}
.tasks {
list-style-type: none;
padding-inline-start: 0;
padding-left: 16px;
padding-right: 16px;
margin-block-start: 0;
margin-block-end: 0;
}
.tasks > li {
display: flex;
padding: 16px;
border-bottom: #eee solid 1px;
align-items: center;
}
.tasks > li > label {
flex-grow: 1;
}
.tasks > li > button {
justify-self: flex-end;
background-color: #ff3046;
}
```
:::
> If you want to learn more about this stylesheet check this article about [Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/), and also this free [video tutorial](https://flexbox.io/) about it from [Wes Bos](https://twitter.com/wesbos).
>
> Flexbox is an excellent tool to distribute and align elements in your UI.
### 5.2: Applying styles
Now you need to add some elements around your components. You are going to add a `class` to your main div in the `App`, also a `header` element with a few `divs` around your `h1`, and a main `div` around your form and list. Check below how it should be, pay attention to the name of the classes, they need to be the same as in the CSS file:
::: code-group
```html [imports/ui/App.html]
...
<template name="mainContainer">
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ Todo List</h1>
</div>
</div>
</header>
<div class="main">
{{> form }}
<ul class="tasks">
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
</div>
</template>
...
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step05-styles.png"/>
In the next step, we are going to make this task list more interactive, for example, providing a way to filter tasks.

View File

@@ -0,0 +1,204 @@
## 6: Filter tasks
In this step, you will filter your tasks by status and show the number of pending tasks.
### 6.1: ReactiveDict
First, you will add a button to show or hide the completed tasks from the list.
To keep the state, we will use the `ReactiveDict`, a reactive dictionary which enables us to store an arbitrary set of key-value pairs. Use it to manage the internal state in your components, i.e. the currently selected item in a list. To know more about how `ReactiveDict` works, you can click on this [link](https://docs.meteor.com/api/reactive-dict.html), and there you will find everything you need to know and everything you can do with it.
We need to install the `reactive-dict` package in our app. Simply run the command below on your app root directory:
```shell
meteor add reactive-dict
```
Next, we need to set up a new `ReactiveDict` and attach it to the `mainContainer` template instance (as this is where well store the buttons state) when it is first created. The best place to create our variables is inside the callback onCreated of the template that we want to persist our data. This callback is called as soon as the template renders on the screen:
::: code-group
```js [imports/ui/App.js]
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import { TasksCollection } from "../api/TasksCollection";
import '/imports/api/TasksMethods.js'; // this import in this client UI allows for optimistic execution
import './App.html';
import './Task';
Template.mainContainer.onCreated(function mainContainerOnCreated() {
this.state = new ReactiveDict();
Meteor.subscribe('tasks');
});
...
```
:::
Then, we need an event handler to update the `ReactiveDict` variable when the button is clicked. An event handler takes two arguments, the second of which is the same template instance in the onCreated callback. Also, create a new constant called `HIDE_COMPLETED_STRING` below the imports, that will be used throughout the code as the name of the variable we are persisting:
::: code-group
```js [imports/ui/App.js]
...
const HIDE_COMPLETED_STRING = "hideCompleted";
...
Template.mainContainer.events({
"click #hide-completed-button"(event, instance) {
const currentHideCompleted = instance.state.get(HIDE_COMPLETED_STRING);
instance.state.set(HIDE_COMPLETED_STRING, !currentHideCompleted);
}
});
...
```
:::
The button in the UI to toggle our state will look something like this:
::: code-group
```html [imports/ui/App.html]
...
<div class="main">
{{> form }}
<div class="filter">
<button id="hide-completed-button">
{{#if hideCompleted}}
Show All
{{else}}
Hide Completed
{{/if}}
</button>
</div>
<ul class="tasks">
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</div>
...
```
:::
You may notice were using `if` (a conditional test) for the first time, and its pretty straightforward. You can learn more about the conditional test, `if`, [here](https://guide.meteor.com/v1.3/blaze.html#builtin-block-helpers). Were also using a helper called `hideCompleted` that we didnt create yet, but we will shortly.
### 6.2: Button style
You should add some style to your button so it does not look gray and without a good contrast. You can use the styles below as a reference:
::: code-group
```css [client/main.css]
.filter {
display: flex;
justify-content: center;
}
.filter > button {
background-color: #62807e;
}
```
:::
### 6.3: Filter Tasks
Now, we need to update `Template.mainContainer.helpers`. The code below verifies if the variable `hideCompleted` is set to true and if yes, we filter our query to get non completed tasks. We also have a new helper called `hideCompleted` that will help us in the UI where we want to know if were filtering or not:
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.helpers({
tasks() {
const instance = Template.instance();
const hideCompleted = instance.state.get(HIDE_COMPLETED_STRING);
const hideCompletedFilter = { isChecked: { $ne: true } };
return TasksCollection.find(hideCompleted ? hideCompletedFilter : {}, {
sort: { createdAt: -1, _id: -1 },
}).fetch();
},
hideCompleted() {
return Template.instance().state.get(HIDE_COMPLETED_STRING);
},
});
...
```
:::
### 6.4: Meteor Dev Tools Extension
You can install an extension to visualize the data in your Mini Mongo.
[Meteor DevTools Evolved](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf) will help you to debug your app as you can see what data is on Mini Mongo.
<img width="800px" src="/tutorials/blaze/assets/step06-extension.png"/>
You can also see all the messages that Meteor is sending and receiving from the server, this is useful for you to learn more about how Meteor works.
<img width="800px" src="/tutorials/blaze/assets/step06-ddp-messages.png"/>
Install it in your Google Chrome browser using this [link](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf).
### 6.5: Pending tasks
Update the App component in order to show the number of pending tasks in the app bar.
You should avoid adding zero to your app bar when there are no pending tasks.
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.helpers({
...,
incompleteCount() {
const incompleteTasksCount = TasksCollection.find({ isChecked: { $ne: true } }).count();
return incompleteTasksCount ? `(${incompleteTasksCount})` : '';
},
});
...
```
:::
::: code-group
```html [imports/ui/App.html]
...
<template name="mainContainer">
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ To Do List {{incompleteCount}}</h1>
</div>
</div>
</header>
...
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step06-all.png"/>
<img width="200px" src="/tutorials/blaze/assets/step06-filtered.png"/>
In the next step we are going to include user access in your app.

View File

@@ -0,0 +1,438 @@
## 7: Adding User Accounts
### 7.1: Password Authentication
Meteor already comes with a basic authentication and account management system out of the box, so you only need to add the `accounts-password` to enable username and password authentication:
```shell
meteor add accounts-password
```
> There are many more authentication methods supported. You can read more about the accounts system [here](https://v3-docs.meteor.com/api/accounts.html).
We also recommend you to install `bcrypt` node module, otherwise, you are going to see a warning saying that you are using a pure-Javascript implementation of it.
```shell
meteor npm install --save bcrypt
```
> You should always use `meteor npm` instead of only `npm` so you always use the `npm` version pinned by Meteor, this helps you to avoid problems due to different versions of npm installing different modules.
### 7.2: Create User Account
Now you can create a default user for our app, we are going to use `meteorite` as username, we just create a new user on server startup if we didn't find it in the database.
::: code-group
```js [server/main.js]
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksMethods";
const SEED_USERNAME = 'meteorite';
const SEED_PASSWORD = 'password';
Meteor.startup(async () => {
if (!(await Accounts.findUserByUsername(SEED_USERNAME))) {
await Accounts.createUser({
username: SEED_USERNAME,
password: SEED_PASSWORD,
});
}
...
});
```
:::
You should not see anything different in your app UI yet.
### 7.3: Login Form
You need to provide a way for the users to input the credentials and authenticate, for that we need a form.
Our login form will be simple, with just two fields (username and password) and a button. You should use `Meteor.loginWithPassword(username, password)`; to authenticate your user with the provided inputs.
::: code-group
```html [imports/ui/Login.html]
<template name="login">
<form class="login-form">
<div>
<label htmlFor="username">Username</label>
<input
type="text"
placeholder="Username"
name="username"
required
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
type="password"
placeholder="Password"
name="password"
required
/>
</div>
<div>
<button type="submit">Log In</button>
</div>
</form>
</template>
```
:::
::: code-group
```js [imports/ui/Login.js]
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import './Login.html';
Template.login.events({
'submit .login-form'(e) {
e.preventDefault();
const target = e.target;
const username = target.username.value;
const password = target.password.value;
Meteor.loginWithPassword(username, password);
}
});
```
:::
Be sure also to import the login form in `App.js`.
::: code-group
```js [imports/ui/App.js]
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import { TasksCollection } from "../api/TasksCollection";
import '/imports/api/TasksMethods.js'; // this import in this client UI allows for optimistic execution
import './App.html';
import './Task';
import "./Login.js";
...
```
:::
Ok, now you have a form, let's use it.
### 7.4: Require Authentication
Our app should only allow an authenticated user to access its task management features.
We can accomplish that by rendering the `Login` from the template when we dont have an authenticated user. Otherwise, we return the form, filter, and list component.
To achieve this, we will use a conditional test inside our main div on `App.html`:
::: code-group
```html [imports/ui/App.html]
...
<div class="main">
{{#if isUserLoggedIn}}
{{> form }}
<div class="filter">
<button id="hide-completed-button">
{{#if hideCompleted}}
Show All
{{else}}
Hide Completed
{{/if}}
</button>
</div>
<ul class="tasks">
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
{{else}}
{{> login }}
{{/if}}
</div>
...
```
:::
As you can see, if the user is logged in, we render the whole app (`isUserLoggedIn`). Otherwise, we render the Login template. Lets now create our helper `isUserLoggedIn`:
::: code-group
```js [imports/ui/App.js]
...
const getUser = () => Meteor.user();
const isUserLoggedInChecker = () => Boolean(getUser());
...
Template.mainContainer.helpers({
...,
isUserLoggedIn() {
return isUserLoggedInChecker();
},
});
...
```
:::
### 7.5: Login Form style
Ok, let's style the login form now:
::: code-group
```css [client/main.css]
.login-form {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
align-items: center;
}
.login-form > div {
margin: 8px;
}
.login-form > div > label {
font-weight: bold;
}
.login-form > div > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
margin-top: 4px;
}
.login-form > div > input:focus {
outline: 0;
}
.login-form > div > button {
background-color: #62807e;
}
```
:::
Now your login form should be centralized and beautiful.
### 7.6: Server startup
Every task should have an owner from now on. So go to your database, as you learn before, and remove all the tasks from there:
`db.tasks.remove({});`
Change your `server/main.js` to add the seed tasks using your `meteorite` user as owner.
Make sure you restart the server after this change so `Meteor.startup` block will run again. This is probably going to happen automatically anyway as you are going to make changes in the server side code.
::: code-group
```js [server/main.js]
...
const user = await Accounts.findUserByUsername(SEED_USERNAME);
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", {
text: taskName,
createdAt: new Date(),
userId: user._id
});
});
}
...
```
:::
See that we are using a new field called `userId` with our user `_id` field, we are also setting `createdAt` field.
### 7.7: Task owner
First, let's change our publication to publish the tasks only for the currently logged user. This is important for security, as you send only data that belongs to that user.
::: code-group
```js [/imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
let result = this.ready();
const userId = this.userId;
if (userId) {
result = TasksCollection.find({ userId });
}
return result;
});
```
:::
Now let's check if we have a `user` before trying to fetch any data:
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.helpers({
tasks() {
let result = [];
if (isUserLoggedInChecker()) {
const instance = Template.instance();
const hideCompleted = instance.state.get(HIDE_COMPLETED_STRING);
const hideCompletedFilter = { isChecked: { $ne: true } };
result = TasksCollection.find(hideCompleted ? hideCompletedFilter : {}, {
sort: { createdAt: -1, _id: -1 },
}).fetch();
}
return result;
},
hideCompleted() {
return Template.instance().state.get(HIDE_COMPLETED_STRING);
},
incompleteCount() {
result = '';
if (isUserLoggedInChecker()) {
const incompleteTasksCount = TasksCollection.find({ isChecked: { $ne: true } }).count();
result = incompleteTasksCount ? `(${incompleteTasksCount})` : '';
}
return result;
},
isUserLoggedIn() {
return isUserLoggedInChecker();
},
});
...
```
:::
Also, update the `tasks.insert` method to include the field `userId` when creating a new task:
::: code-group
```js [imports/api/TasksMethods.js]
...
Meteor.methods({
"tasks.insert"(doc) {
const insertDoc = { ...doc };
if (!('userId' in insertDoc)) {
insertDoc.userId = this.userId;
}
return TasksCollection.insertAsync(insertDoc);
},
...
```
:::
### 7.8: Log out
We can also organize our tasks by showing the owners username below our app bar. Lets add a new `div` where the user can click and log out from the app:
::: code-group
```html [imports/ui/App.html]
...
<div class="main">
{{#if isUserLoggedIn}}
<div class="user">
{{getUser.username}} 🚪
</div>
{{> form }}
...
```
:::
Now, lets create the `getUser` helper and implement the event that will log out the user when they click on this `div`. Logging out is done by calling the function `Meteor.logout()`:
::: code-group
```js [imports/ui/App.js]
...
Template.mainContainer.events({
...,
'click .user'() {
Meteor.logout();
},
});
...
Template.mainContainer.helpers({
...,
getUser() {
return getUser();
},
});
...
```
:::
Remember to style your username as well.
::: code-group
```css [client/main.css]
.user {
display: flex;
align-self: flex-end;
margin: 8px 16px 0;
font-weight: bold;
cursor: pointer;
}
```
:::
Phew! You have done quite a lot in this step. Authenticated the user, set the user in the tasks, and provided a way for the user to log out.
Your app should look like this:
<img width="200px" src="/tutorials/blaze/assets/step07-login.png"/>
<img width="200px" src="/tutorials/blaze/assets/step07-logout.png"/>
In the next step, we are going to learn how to deploy your app!

View File

@@ -0,0 +1,98 @@
## 8: Deploying
Deploying a Meteor application is similar to deploying any other Node.js app that uses websockets. You can find deployment options in [our guide](https://guide.meteor.com/deployment), including Meteor Up, Docker, and our recommended method, Galaxy.
In this tutorial, we will deploy our app on [Galaxy](https://galaxycloud.app/), which is our own cloud solution. Galaxy offers a free plan, so you can deploy and test your app. Pretty cool, right?
### 8.1: Create your account
You need a Meteor account to deploy your apps. If you dont have one yet, you can [sign up here](https://cloud.meteor.com/?isSignUp=true).
With this account, you can access our package manager, [Atmosphere](https://atmospherejs.com/), [Forums](https://forums.meteor.com/) and more.
### 8.2: Set up MongoDB (Optional)
As your app uses MongoDB the first step is to set up a MongoDB database, Galaxy offers MongoDB hosting on a free plan for testing purposes, and you can also request for a production ready database that allows you to scale.
In any MongoDB provider you will have a MongoDB URL which you must use. If you use the free option provided by Galaxy, the initial setup is done for you.
Galaxy MongoDB URL will be like this: `mongodb://username:<password>@org-dbname-01.mongodb.galaxy-cloud.io` .
> You can read more about Galaxy MongoDB [here](https://galaxy-support.meteor.com/en/article/mongodb-general-1syd5af/).
### 8.3: Set up settings
If you are not using the free option, then you need to create a settings file. Its a JSON file that Meteor apps can read configurations from. Create this file in a new folder called `private` in the root of your project. It is important to notice that `private` is a special folder that is not going to be published to the client side of your app.
Make sure you replace `Your MongoDB URL` by your own MongoDB URL :)
::: code-group
```json [private/settings.json]
{
"galaxy.meteor.com": {
"env": {
"MONGO_URL": "Your MongoDB URL"
}
}
}
```
:::
### 8.4: Deploy it
Now you are ready to deploy, run `meteor npm install` before deploying to make sure all your dependencies are installed.
You also need to choose a subdomain to publish your app. We are going to use the main domain `meteorapp.com` that is free and included on any Galaxy plan.
In this example we are going to use `blaze-meteor-3.meteorapp.com` but make sure you select a different one, otherwise you are going to receive an error.
> You can learn how to use custom domains on Galaxy [here](https://galaxy-support.meteor.com/en/article/domains-16cijgc/). Custom domains are available starting with the Essentials plan.
Run the deployment command:
```shell
meteor deploy blaze-meteor-3.meteorapp.com --free --mongo
```
> If you are not using the free hosting with MongoDB on Galaxy, then remove the `--mongo` flag from the deploy script and add `--settings private/settings.json` with the proper setting for your app.
Make sure you replace `blaze-meteor-3` by a custom name that you want as subdomain. You will see a log like this:
```shell
meteor deploy blaze-meteor-3.meteorapp.com --settings private/settings.json
Talking to Galaxy servers at https://us-east-1.galaxy-deploy.meteor.com
Preparing to build your app...
Preparing to upload your app...
Uploaded app bundle for new app at blaze-meteor-3.meteorapp.com.
Galaxy is building the app into a native image.
Waiting for deployment updates from Galaxy...
Building app image...
Deploying app...
You have successfully deployed the first version of your app.
For details, visit https://galaxy.meteor.com/app/blaze-meteor-3.meteorapp.com
```
This process usually takes just a few minutes, but it depends on your internet speed as its going to send your app bundle to Galaxy servers.
> Galaxy builds a new Docker image that contains your app bundle and then deploy containers using it, [read more](https://galaxy-support.meteor.com/en/article/container-environment-lfd6kh/).
You can check your logs on Galaxy, including the part that Galaxy is building your Docker image and deploying it.
### 8.5: Access the app and enjoy
Now you should be able to access your Galaxy dashboard at `https://galaxy.meteor.com/app/blaze-meteor-3.meteorapp.com`.
You can also access your app on Galaxy 2.0 which is currently in beta at `https://galaxy-beta.meteor.com/<your-username>/us-east-1/apps/<your-app-name>.meteorapp.com`. Remember to use your own subdomain instead of `blaze-meteor-3`.
You can access the app at [blaze-meteor-3.meteorapp.com](https://blaze-meteor-3.meteorapp.com/)! Just use your subdomain to access yours!
> We deployed to Galaxy running in the US (us-east-1), we also have Galaxy running in other regions in the world, check the list [here](https://galaxy-support.meteor.com/en/article/regions-1vucejm/).
This is huge, you have your app running on Galaxy, ready to be used by anyone in the world!

View File

@@ -0,0 +1,17 @@
## 9: Next Steps
You have completed the tutorial!
By now, you should have a good understanding of working with Meteor and Blaze.
::: info
You can find the final version of this app in our [GitHub repository](https://github.com/meteor/meteor3-blaze).
:::
Here are some options for what you can do next:
- Check out the complete [documentation](https://v3-docs.meteor.com/) to learn more about Meteor 3.
- Read the [Galaxy Guide](https://galaxy-support.meteor.com/en/article/deploy-to-galaxy-18gd6e2/) to learn more about deploying your app.
- Join our community on the [Meteor Forums](https://forums.meteor.com/) and the [Meteor Lounge on Discord](https://discord.gg/hZkTCaVjmT) to ask questions and share your experiences.
We can't wait to see what you build next!

Binary file not shown.

After

Width:  |  Height:  |  Size: 218 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

View File

@@ -0,0 +1,25 @@
# Meteor.js 3 + Blaze
In this tutorial, we will create a simple To-Do app using [Blaze](https://www.blazejs.org/) and Meteor 3.0. Meteor works well with other frameworks like [React](https://react.dev/), [Vue 3](https://vuejs.org/), [Solid](https://www.solidjs.com/), and [Svelte](https://svelte.dev/).
Blaze was created as part of Meteor when it launched in 2011, React was created by Facebook in 2013. Both have been used successfully by large production apps. Blaze is the easiest to learn and has the most full-stack Meteor packages, but React is more developed and has a larger community. Vue, Solid and Svelte are newer UI frameworks that some teams prefer. Choose what you like but learning Blaze is always a good idea because you may want to use Blaze UI packages with your app even if you are using something like React. The [accounts-ui](https://docs.meteor.com/packages/accounts-ui) package is a good example.
Blaze is a powerful library for creating user interfaces by writing reactive HTML templates using an easy-to-learn Handlebars-like template syntax. If you are new and not sure what UI framework to use, Blaze is a great place to start. Compared to using a combination of traditional templates and jQuery, Blaze eliminates the need for all the “update logic” in your app that listens for data changes and manipulates the DOM. Instead, familiar template directives like <span v-pre>{{#if}}</span> and <span v-pre>{{#each}}</span> integrates with [Trackers](https://docs.meteor.com/api/tracker.html) “transparent reactivity” and [Minimongos](https://docs.meteor.com/api/collections.html) database cursors so that the DOM updates automatically.
To start building your Blaze app, you'll need a code editor. If you're unsure which one to choose, [Visual Studio Code](https://code.visualstudio.com/) is a good option.
Lets begin building your app!
# Table of Contents
[[toc]]
<!-- @include: ./1.creating-the-app.md-->
<!-- @include: ./2.collections.md-->
<!-- @include: ./3.forms-and-events.md-->
<!-- @include: ./4.update-and-remove.md-->
<!-- @include: ./5.styles.md-->
<!-- @include: ./6.filter-tasks.md-->
<!-- @include: ./7.adding-user-accounts.md-->
<!-- @include: ./8.deploying.md-->
<!-- @include: ./9.next-steps.md-->

View File

@@ -103,9 +103,7 @@ You should avoid adding zero to your app bar when there are no pending tasks.
TasksCollection.find(hideCompletedFilter).count()
);
const pendingTasksTitle = `${
pendingTasksCount ? ` (${pendingTasksCount})` : ''
}`;
const pendingTasksTitle = pendingTasksCount ? ` (${pendingTasksCount})` : '';
..
<h1>

View File

@@ -0,0 +1,200 @@
## 1: Creating the app
### 1.1: Install Meteor
First, we need to install Meteor by following this [installation guide](https://docs.meteor.com/about/install.html).
### 1.2: Create Meteor Project
The easiest way to setup Meteor with Solid is by using the command `meteor create` with the option `--solid` and your project name:
```shell
meteor create --solid simple-todos-solid
```
Meteor will create all the necessary files for you.
The files located in the `client` directory are setting up your client side (web), you can see for example `client/main.html` where Meteor is rendering your App main component into the HTML.
Also, check the `server` directory where Meteor is setting up the server side (Node.js), you can see the `server/main.js` which would be a good place to initialize your MongoDB database with some data. You don't need to install MongoDB as Meteor provides an embedded version of it ready for you to use.
You can now run your Meteor app using:
```shell
meteor
```
Don't worry, Meteor will keep your app in sync with all your changes from now on.
Take a quick look at all the files created by Meteor, you don't need to understand them now but it's good to know where they are.
Your Solid code will be located inside the `imports/ui` directory, and the `App.jsx` file will be the root component of your Solid To-do app.
### 1.3: Create Tasks
To start working on our todo list app, lets replace the code of the default starter app with the code below. From there, well talk about what it does.
First, lets simplify our HTML entry point like so:
::: code-group
```html [client/main.html]
<head>
<title>Simple todo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
```
:::
The `imports/ui/main.jsx` file should import and render the main Solid component (note: this is referenced via `client/main.js` which imports it):
::: code-group
```jsx [imports/ui/main.jsx]
/* @refresh reload */
import { render } from 'solid-js/web';
import { App } from './App';
import { Meteor } from "meteor/meteor";
import './main.css';
Meteor.startup(() => {
render(() => <App/>, document.getElementById('root'));
});
```
:::
::: code-group
```js [client/main.js]
import '../imports/ui/main';
```
:::
Inside the `imports/ui` folder let us modify `App.jsx` to display a header and a list of tasks:
::: code-group
```jsx [imports/ui/App.jsx]
import { For } from "solid-js";
export const App = () => {
const tasks = [
{ text: 'This is task 1' },
{ text: 'This is task 2' },
{ text: 'This is task 3' },
];
return (
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<ul>
<For each={tasks}>
{(task) => (
<li>{task.text}</li>
)}
</For>
</ul>
</div>
);
};
```
:::
We just modified our main Solid component `App.jsx`, which will be rendered into the `#root` div in the body. It shows a header and a list of tasks. For now, we're using static sample data to display the tasks.
You can now delete these starter files from your project as we don't need them: `Info.jsx`, `Hello.jsx`
### 1.4: View Sample Tasks
As you are not connecting to your server and database yet, weve defined some sample data directly in `App.jsx` to render a list of tasks.
At this point meteor should be running on port 3000 so you can visit the running app and see your list with three tasks displayed at [http://localhost:3000/](http://localhost:3000/) - but if meteor is not running, go to your terminal and move to the top directory of your project and type `meteor` then press return to launch the app.
All right! Lets find out what all these bits of code are doing!
### 1.5: Rendering Data
<img width="688px" src="/tutorials/solid/assets/mermaid-diagram-solid-rendering.png"/>
In Solid with Meteor, your main entry point is `client/main.js`, which imports `imports/ui/main.jsx`
to render your root Solid component `App.jsx` to a target element in the HTML like `<div id="root"></div>` using Solid's `render` function.
Solid components are defined in `.jsx` files using JSX syntax, which can include JavaScript logic, imports, and reactive primitives. The JSX markup can use Solid's control flow components, such as `<For>` for looping and <span v-pre>{expression}</span> for interpolating data.
You can define data and logic directly in the component function. In the code above, we defined a `tasks` array directly in the component. Inside the markup, we use <span v-pre>`<For each={tasks}>`</span> to iterate over the array and display each task's `text`
property using <span v-pre>{task.text}</span>.
For Meteor-specific reactivity (like subscriptions and collections), Solid in Meteor integrates with Meteor's Tracker using hooks like effects or custom trackers. We'll cover that in later steps.
### 1.6: Mobile Look
Lets see how your app is looking on mobile. You can simulate a mobile environment by `right clicking` your app in the browser (we are assuming you are using Google Chrome, as it is the most popular browser) and then `inspect`, this will open a new window inside your browser called `Dev Tools`. In the `Dev Tools` you have a small icon showing a Mobile device and a Tablet:
<img width="500px" src="/tutorials/solid/assets/step01-dev-tools-mobile-toggle.png"/>
Click on it and then select the phone that you want to simulate and in the top nav bar.
> You can also check your app in your personal cellphone. To do so, connect to your App using your local IP in the navigation browser of your mobile browser.
>
> This command should print your local IP for you on Unix systems
> `ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'`
>
> On Microsoft Windows try this in a command prompt
> `ipconfig | findstr "IPv4 Address"`
You should see the following:
<img width="200px" src="/tutorials/solid/assets/step01-mobile-without-meta-tags.png"/>
As you can see, everything is small, as we are not adjusting the view port for mobile devices. You can fix this and other similar issues by adding these lines to your `client/main.html` file, inside the `head` tag, after the `title`.
::: code-group
```html [client/main.html]
<head>
<title>Simple todo</title>
<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>
...
```
:::
Now your app should scale properly on mobile devices and look like this:
<img width="200px" src="/tutorials/solid/assets/step01-mobile-with-meta-tags.png"/>
### 1.7: Hot Module Replacement
Meteor uses a package called [hot-module-replacement](https://docs.meteor.com/packages/hot-module-replacement) which is already added for you. This package updates the javascript modules in a running app that were modified during a rebuild. Reduces the feedback cycle while developing, so you can view and test changes quicker (it even updates the app before the build has finished). You are also not going to lose the state, your app code will be updated, and your state will be the same.
By default, when using Solid with Meteor, reactivity is handled by integrating Solid's fine-grained signals and effects with Meteor's Tracker system. This allows real-time updates of the user's screen as data changes in the database without them having to manually refresh. You can achieve this using Tracker.autorun combined with Solid's createEffect or signals for seamless reactivity.
> You can read more about packages [here](https://docs.meteor.com/packages/).
You should also add the package [dev-error-overlay](https://atmospherejs.com/meteor/dev-error-overlay) at this point, so you can see the errors in your web browser.
```shell
meteor add dev-error-overlay
```
You can try to make some mistakes and then you are going to see the errors in the browser and not only in the console.
In the next step we are going to work with our MongoDB database to be able to store our tasks.

View File

@@ -0,0 +1,183 @@
## 2: Collections
Meteor already sets up MongoDB for you. In order to use our database, we need to create a _collection_, which is where we will store our _documents_, in our case our `tasks`.
> You can read more about collections [here](https://v3-docs.meteor.com/api/collections.html).
In this step we will implement all the necessary code to have a basic collection for our tasks up and running.
### 2.1: Create Tasks Collection
We can create a new collection to store our tasks by creating a new file at `imports/api/TasksCollection.js` which instantiates a new Mongo collection and exports it.
::: code-group
```js [imports/api/TasksCollection.js]
import { Mongo } from "meteor/mongo";
export const TasksCollection = new Mongo.Collection("tasks");
```
:::
Notice that we stored the file in the `imports/api` directory, which is a place to store API-related code, like publications and methods. You can name this folder as you want, this is just a choice.
If there is a `imports/api/links.js` file from the starter project, you can delete that now as we don't need it.
> You can read more about app structure and imports/exports [here](http://guide.meteor.com/structure.html).
### 2.2: Initialize Tasks Collection
For our collection to work, you need to import it in the server so it sets some plumbing up.
You can either use `import "/imports/api/TasksCollection"` or `import { TasksCollection } from "/imports/api/TasksCollection"` if you are going to use on the same file, but make sure it is imported.
Now it is easy to check if there is data or not in our collection, otherwise, we can insert some sample data easily as well.
You don't need to keep the old content of `server/main.js`.
::: code-group
```js [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
const insertTask = async (taskText) =>
await TasksCollection.insertAsync({ text: taskText });
Meteor.startup(async () => {
if (await TasksCollection.find().countAsync() === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach(insertTask);
}
});
```
:::
So you are importing the `TasksCollection` and adding a few tasks to it iterating over an array of strings and for each string calling a function to insert this string as our `text` field in our `task` document.
### 2.3: Render Tasks Collection
Now comes the fun part, you will render the tasks with Solid. That will be pretty simple.
In your `App.jsx` file, import the `TasksCollection` and use Tracker to subscribe and fetch the tasks reactively:
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
export const App = () => {
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find().fetchAsync());
});
return (
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul>
<For each={tasks()}>
{(task) => (
<li>{task.text}</li>
)}
</For>
</ul>
</Show>
</div>
);
};
```
:::
But wait! Something is missing. If you run your app now, you'll see that you don't render any tasks.
That's because we need to publish our data to the client.
> For more information on Publications/Subscriptions, please check our [docs](https://v3-docs.meteor.com/api/meteor.html#pubsub).
Meteor doesn't need REST calls. It instead relies on synchronizing the MongoDB on the server with a MiniMongoDB on the client. It does this by first publishing collections on the server and then subscribing to them on the client.
First, create a publication for our tasks:
::: code-group
```javascript [imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
return TasksCollection.find();
});
```
:::
Now, we need to import this file in our server:
::: code-group
```js [server/main.js]
...
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksPublications"; // [!code highlight]
const insertTask = taskText => TasksCollection.insertAsync({ text: taskText });
...
```
:::
The only thing left is subscribe to this publication, which we've already added in `App.jsx` using:
::: code-group
```jsx [imports/ui/App.jsx]
...
const subscription = Meteor.subscribe("tasks");
...
```
:::
See how your app should look like now:
<img width="200px" src="/tutorials/solid/assets/collections-tasks-list.png"/>
You can change your data on MongoDB in the server and your app will react and re-render for you.
You can connect to your MongoDB running `meteor mongo` in the terminal from your app folder or using a Mongo UI client, like [NoSQLBooster](https://nosqlbooster.com/downloads). Your embedded MongoDB is running in port `3001`.
See how to connect:
<img width="500px" src="/tutorials/solid/assets/collections-connect-db.png"/>
See your database:
<img width="500px" src="/tutorials/solid/assets/collections-see-database.png"/>
You can double-click your collection to see the documents stored on it:
<img width="500px" src="/tutorials/solid/assets/collections-documents.png"/>
In the next step, we are going to create tasks using a form.

View File

@@ -0,0 +1,248 @@
## 3: Forms and Events
All apps need to allow the user to perform some sort of interaction with the data that is stored. In our case, the first type of interaction is to insert new tasks. Without it, our To-Do app wouldn't be very helpful.
One of the main ways in which a user can insert or edit data on a website is through forms. In most cases, it is a good idea to use the `<form>` tag since it gives semantic meaning to the elements inside it.
### 3.1: Create Task Form
Create a new `form` inside the `App.jsx` file, and inside well add an input field and a button. Place it between the `header` and the `Show` elements:
::: code-group
```jsx [imports/ui/App.jsx]
...
</header>
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<Show
...
```
:::
In the code above, we've integrated the form directly into the `App.jsx` component, positioning it above the task list. We're using Solid's signals for two-way binding on the input (via `value` and `onInput`) and an `onSubmit` handler for form submission.
Let's now add our signals and `addTask()` function handler inside the top of the `App` function definition. It will call a Meteor method `tasks.insert` that isn't yet created but we'll soon make:
::: code-group
```jsx [imports/ui/App.jsx]
...
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const subscription = Meteor.subscribe("tasks");
...
```
:::
Altogether, our file should look like:
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find().fetchAsync());
});
return (
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul>
<For each={tasks()}>
{(task) => (
<li>{task.text}</li>
)}
</For>
</ul>
</Show>
</div>
);
};
```
:::
### 3.2: Update the Stylesheet
You also can style it as you wish. For now, we only need some margin at the top so the form doesn't seem off the mark. Add the CSS class `.task-form`, this needs to be the same name in your `class` attribute in the form element. Notice how in Solid you don't use `className` like you would in React.
::: code-group
```css [imports/ui/main.css]
...
.task-form {
margin-top: 1rem;
}
...
```
:::
### 3.3: Add Submit Handler
Now let's create a function to handle the form submit and insert a new task into the database. To do it, we will need to implement a Meteor Method.
Methods are essentially RPC calls to the server that let you perform operations on the server side securely. You can read more about Meteor Methods [here](https://guide.meteor.com/methods.html).
To create your methods, you can create a file called `TasksMethods.js`.
::: code-group
```javascript [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
"tasks.insert"(doc) {
return TasksCollection.insertAsync(doc);
},
});
```
:::
Remember to import your method on the `main.js` server file, delete the `insertTask` function, and invoke the new meteor method inside the `forEach` block.
::: code-group
```javascript [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
import "../imports/api/TasksPublications";
import "../imports/api/TasksMethods"; // [!code highlight]
Meteor.startup(async () => {
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", { // [!code highlight]
text: taskName, // [!code highlight]
createdAt: new Date(), // [!code highlight]
});
});
}
});
```
:::
Inside the `forEach` function, we are adding a task to the `tasks` collection by calling `Meteor.callAsync()`. The first argument is the name of the method we want to call, and the second argument is the text of the task.
Also, insert a date `createdAt` in your `task` document so you know when each task was created.
Now we need to import `TasksMethods.js` in a client-side file to enable optimistic UI (e.g., in `imports/ui/main.jsx`):
::: code-group
```jsx [imports/ui/main.jsx]
/* @refresh reload */
import { render } from 'solid-js/web';
import { App } from './App';
import { Meteor } from "meteor/meteor";
import './main.css';
import "/imports/api/TasksMethods"; // [!code highlight] // this import allows for optimistic execution
Meteor.startup(() => {
render(() => <App/>, document.getElementById('root'));
});
```
:::
In the `addTask` function (shown in 3.1), we prevent the default form submission, get the input value, call the Meteor method to insert the task optimistically, and clear the input.
Meteor methods execute optimistically on the client using MiniMongo while simultaneously calling the server. If the server call fails, MiniMongo rolls back the change, providing a speedy user experience. It's a bit like [rollback netcode](https://glossary.infil.net/?t=Rollback%20Netcode) in fighting video games.
### 3.4: Show Newest Tasks First
Now you just need to make a change that will make users happy: we need to show the newest tasks first. We can accomplish this quite quickly by sorting our [Mongo](https://guide.meteor.com/collections.html#mongo-collections) query.
::: code-group
```jsx [imports/ui/App.jsx]
...
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find({}, { sort: { createdAt: -1 } }).fetchAsync()); // [!code highlight]
});
...
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step03-form-new-task.png"/>
<img width="200px" src="/tutorials/solid/assets/step03-new-task-on-list.png"/>
In the next step, we are going to update your tasks state and provide a way for users to remove tasks.

View File

@@ -0,0 +1,216 @@
## 4: Update and Remove
Up until now, you have only inserted documents into our collection. Let's take a look at how you can update and remove them by interacting with the user interface.
### 4.1: Add Checkbox
First, you need to add a `checkbox` element to your `Task` component.
Next, lets create a new file for our `task` in `imports/ui/Task.jsx`, so we can start to separate the logic in our app.
::: code-group
```jsx [imports/ui/Task.jsx]
import { Meteor } from "meteor/meteor";
export const Task = (props) => {
const { task } = props;
const toggleChecked = async () => {
await Meteor.callAsync("tasks.toggleChecked", { _id: task._id, isChecked: task.isChecked });
};
return (
<li>
<label>
<input type="checkbox" checked={task.isChecked} onChange={toggleChecked} />
<span>{task.text}</span>
</label>
</li>
);
};
```
:::
Now, update `App.jsx` to import and use the `Task` component in the `<For>` loop. Remove the old `<li>` markup.
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
import { Task } from "./Task.jsx"; // [!code highlight]
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find({}, { sort: { createdAt: -1 } }).fetchAsync());
});
return (
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul>
<For each={tasks()}>
{(task) => (
<Task task={task} /> // [!code highlight]
)}
</For>
</ul>
</Show>
</div>
);
};
```
:::
### 4.2: Toggle Checkbox
Now you can update your task document by toggling its `isChecked` field.
First, create a new method called `tasks.toggleChecked` to update the `isChecked` property.
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
...
"tasks.toggleChecked"({ _id, isChecked }) {
return TasksCollection.updateAsync(_id, {
$set: { isChecked: !isChecked },
});
},
});
```
:::
In `Task.jsx` (as shown above), we've added an `onChange` handler that calls the method to toggle the checked state.
Toggling checkboxes should now persist in the DB even if you refresh the web browser.
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step04-checkbox.png"/>
If your computer is fast enough, it's possible that when it sets up the default tasks a few will have the same date. That will cause them to non-deterministically "jump around" in the UI as you toggle checkboxes and the UI reactively updates. To make it stable, you can add a secondary sort on the `_id` of the task:
::: code-group
```jsx [imports/ui/App.jsx]
...
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetchAsync()); // [!code highlight]
});
...
```
:::
### 4.3: Remove tasks
You can remove tasks with just a few lines of code.
First, add a button after the `label` in your `Task` component and a `deleteTask` function.
::: code-group
```jsx [imports/ui/Task.jsx]
import { Meteor } from "meteor/meteor";
export const Task = (props) => {
const { task } = props;
const toggleChecked = async () => {
await Meteor.callAsync("tasks.toggleChecked", { _id: task._id, isChecked: task.isChecked });
};
const deleteTask = async () => { // [!code highlight]
await Meteor.callAsync("tasks.delete", { _id: task._id }); // [!code highlight]
}; // [!code highlight]
return (
<li>
<label>
<input type="checkbox" checked={task.isChecked} onChange={toggleChecked} />
<span>{task.text}</span>
</label>
<button class="delete" onClick={deleteTask}>&times;</button> // [!code highlight]
</li>
);
};
```
:::
Next you need to have a function to delete the task. For that, let's create a new method called `tasks.delete`:
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
...
"tasks.delete"({ _id }) {
return TasksCollection.removeAsync(_id);
},
});
```
:::
Now the removal logic is handled in `Task.jsx` via the `onClick` event on the delete button, which calls the Meteor method.
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step04-delete-button.png"/>
### 4.4: Getting data in event handlers
In a collection, every inserted document has a unique `_id` field that can refer to that specific document. Inside the component, the `task` prop provides access to the task object, including its `_id`
and other fields like `isChecked` and `text`. We use these to call Meteor methods for updating or removing the specific task.
In the next step, we are going to improve the look of your app using CSS with Flexbox.

View File

@@ -0,0 +1,231 @@
## 5: Styles
### 5.1: CSS
Our user interface up until this point has looked quite ugly. Let's add some basic styling which will serve as the foundation for a more professional looking app.
Replace the content of our `imports/ui/main.css` file with the one below, the idea is to have an app bar at the top, and a scrollable content including:
- form to add new tasks;
- list of tasks.
::: code-group
```css [imports/ui/main.css]
body {
font-family: sans-serif;
background-color: #315481;
background-image: linear-gradient(to bottom, #315481, #918e82 100%);
background-attachment: fixed;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
font-size: 14px;
}
button {
font-weight: bold;
font-size: 1em;
border: none;
color: white;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
padding: 5px;
cursor: pointer;
}
button:focus {
outline: 0;
}
.app {
display: flex;
flex-direction: column;
height: 100vh;
}
.app-header {
flex-grow: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.main {
display: flex;
flex-direction: column;
flex-grow: 1;
overflow: auto;
background: white;
}
.main::-webkit-scrollbar {
width: 0;
height: 0;
background: inherit;
}
header {
background: #d2edf4;
background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
padding: 20px 15px 15px 15px;
position: relative;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
}
.app-bar {
display: flex;
justify-content: space-between;
}
.app-bar h1 {
font-size: 1.5em;
margin: 0;
display: inline-block;
margin-right: 1em;
}
.task-form {
display: flex;
margin: 16px;
}
.task-form > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
}
.task-form > input:focus {
outline: 0;
}
.task-form > button {
min-width: 100px;
height: 95%;
background-color: #315481;
}
.tasks {
list-style-type: none;
padding-inline-start: 0;
padding-left: 16px;
padding-right: 16px;
margin-block-start: 0;
margin-block-end: 0;
}
.tasks > li {
display: flex;
padding: 16px;
border-bottom: #eee solid 1px;
align-items: center;
}
.tasks > li > label {
flex-grow: 1;
}
.tasks > li > button {
justify-self: flex-end;
background-color: #ff3046;
}
```
:::
> If you want to learn more about this stylesheet check this article about [Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/), and also this free [video tutorial](https://flexbox.io/) about it from [Wes Bos](https://twitter.com/wesbos).
>
> Flexbox is an excellent tool to distribute and align elements in your UI.
### 5.2: Applying styles
Now you need to add some elements around your components. You are going to add a `class` to your main `div` in the `App.jsx`, also a `header` element with a few `div` elements around your `h1`, and a main `div` around your form and list. Check below how it should be; pay attention to the name of the classes, they need to be the same as in the CSS file:
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
import { Task } from "./Task.jsx";
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetchAsync());
});
return (
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ Todo List</h1>
</div>
</div>
</header>
<div class="main">
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul class="tasks">
<For each={tasks()}>
{(task) => (
<Task task={task} />
)}
</For>
</ul>
</Show>
</div>
</div>
);
};
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step05-styles.png"/>
In the next step, we are going to make this task list more interactive, for example, providing a way to filter tasks.

View File

@@ -0,0 +1,322 @@
## 6: Filter tasks
In this step, you will filter your tasks by status and show the number of pending tasks.
### 6.1: Reactive State
First, you will add a button to show or hide the completed tasks from the list.
In Solid, we manage component state using signals for reactivity. Solid's fine-grained reactivity will automatically update the UI when the state changes.
We'll add a `hideCompleted` variable to the `App.jsx` component and a function to toggle it.
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
import { Task } from "./Task.jsx";
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const [hideCompleted, setHideCompleted] = createSignal(false); // [!code highlight]
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const toggleHideCompleted = () => { // [!code highlight]
setHideCompleted(!hideCompleted()); // [!code highlight]
}; // [!code highlight]
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
setTasks(await TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetchAsync());
});
// markup will be updated in next steps
};
```
:::
Then, add the button in the markup to toggle the state:
::: code-group
```jsx [imports/ui/App.jsx]
// ... javascript above remains the same
return (
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ Todo List</h1>
</div>
</div>
</header>
<div class="main">
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<div class="filter"> // [!code highlight]
<button onClick={toggleHideCompleted}> // [!code highlight]
<Show // [!code highlight]
when={hideCompleted()} // [!code highlight]
fallback="Hide Completed" // [!code highlight]
> // [!code highlight]
Show All // [!code highlight]
</Show> // [!code highlight]
</button> // [!code highlight]
</div> // [!code highlight]
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul class="tasks">
<For each={tasks()}>
{(task) => (
<Task task={task} />
)}
</For>
</ul>
</Show>
</div>
</div>
);
```
:::
You may notice were using `<Show>` for the button text. You can learn more about Solid's conditional rendering [here](https://docs.solidjs.com/reference/components/show).
### 6.2: Button style
You should add some style to your button so it does not look gray and without a good contrast. You can use the styles below as a reference:
::: code-group
```css [imports/ui/main.css]
.filter {
display: flex;
justify-content: center;
}
.filter > button {
background-color: #62807e;
}
```
:::
### 6.3: Filter Tasks
Now, update the reactive tasks fetch to apply the filter if `hideCompleted` is true. We'll also add a reactive signal for the incomplete count using another Tracker.autorun.
::: code-group
```jsx [imports/ui/App.jsx]
import { createSignal, For, Show } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
import { Task } from "./Task.jsx";
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const [hideCompleted, setHideCompleted] = createSignal(false);
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const toggleHideCompleted = () => {
setHideCompleted(!hideCompleted());
};
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
const query = hideCompleted() ? { isChecked: { $ne: true } } : {}; // [!code highlight]
setTasks(await TasksCollection.find(query, { sort: { createdAt: -1, _id: -1 } }).fetchAsync()); // [!code highlight]
});
// Reactive incomplete count // [!code highlight]
const [incompleteCount, setIncompleteCount] = createSignal(0); // [!code highlight]
Tracker.autorun(async () => { // [!code highlight]
setIncompleteCount(await TasksCollection.find({ isChecked: { $ne: true } }).countAsync()); // [!code highlight]
}); // [!code highlight]
// markup remains the same
};
```
:::
### 6.4: Meteor Dev Tools Extension
You can install an extension to visualize the data in your Mini Mongo.
[Meteor DevTools Evolved](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf) will help you to debug your app as you can see what data is on Mini Mongo.
<img width="800px" src="/tutorials/solid/assets/step06-extension.png"/>
You can also see all the messages that Meteor is sending and receiving from the server, this is useful for you to learn more about how Meteor works.
<img width="800px" src="/tutorials/solid/assets/step06-ddp-messages.png"/>
Install it in your Google Chrome browser using this [link](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf).
### 6.5: Pending tasks
Update the App component in order to show the number of pending tasks in the app bar.
You should avoid adding zero to your app bar when there are no pending tasks. Use the reactive `incompleteCount` in the header:
::: code-group
```jsx [imports/ui/App.jsx]
// ... javascript with incompleteCount remains the same
return (
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ To Do List {incompleteCount() > 0 ? `(${incompleteCount()})` : ''}</h1> // [!code highlight]
</div>
</div>
</header>
// rest of markup
</div>
);
```
:::
### 6.6: Make the Hide/Show toggle work
If you try the Hide/Show completed toggle button you'll see that the text changes but it doesn't actually do anything to the list of tasks. The toggle button isn't triggering the expected filtering because the `hideCompleted` signal (from Solid) isn't integrated with Meteor's Tracker reactivity system. Tracker.autorun only re-runs when its internal dependencies (like subscription data or ReactiveVars) change—not when Solid signals change. So, updating `hideCompleted` via `setHideCompleted` changes the button text (via Solid's `<Show>`), but it doesn't re-execute the autorun to update the query and re-fetch tasks.
This is a common challenge when bridging Solid's fine-grained reactivity with Meteor's Tracker. I'll explain the fix below with minimal changes to your code.
To make Tracker react to changes in `hideCompleted`, we'll use Meteor's `ReactiveVar`
to hold the filter state. This makes the value reactive within Tracker, so the autorun re-runs automatically when it changes. We'll sync it with your Solid signal for the UI.
Add this import at the top of `App.jsx`
::: code-group
```jsx [imports/ui/App.jsx]
import { ReactiveVar } from 'meteor/reactive-var';
```
:::
Initialize a ReactiveVar and use a Solid `createEffect` to keep it in sync with your `hideCompleted` signal. Update your `App` component like this:
Add this import at the top of `App.jsx`
::: code-group
```jsx [imports/ui/App.jsx]
...
import { createSignal, For, Show, createEffect } from "solid-js"; // Updated import
...
export const App = () => {
const [newTask, setNewTask] = createSignal('');
const [hideCompleted, setHideCompleted] = createSignal(false);
// New: ReactiveVar for Tracker integration
const hideCompletedVar = new ReactiveVar(false); // [!code highlight]
// New: Sync Solid signal to ReactiveVar (triggers Tracker re-run) // [!code highlight]
createEffect(() => { // [!code highlight]
hideCompletedVar.set(hideCompleted()); // [!code highlight]
}); // [!code highlight]
const addTask = async (event) => {
event.preventDefault();
if (newTask().trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask(),
createdAt: new Date(),
});
setNewTask('');
}
};
const toggleHideCompleted = () => {
setHideCompleted(!hideCompleted());
};
const subscription = Meteor.subscribe("tasks");
const [isReady, setIsReady] = createSignal(subscription.ready());
const [tasks, setTasks] = createSignal([]);
Tracker.autorun(async () => {
setIsReady(subscription.ready());
// Use ReactiveVar in the query for Tracker reactivity // [!code highlight]
const query = hideCompletedVar.get() ? { isChecked: { $ne: true } } : {}; // [!code highlight]
setTasks(await TasksCollection.find(query, { sort: { createdAt: -1, _id: -1 } }).fetchAsync());
});
// Reactive incomplete count (unchanged)
const [incompleteCount, setIncompleteCount] = createSignal(0);
Tracker.autorun(async () => {
setIncompleteCount(await TasksCollection.find({ isChecked: { $ne: true } }).countAsync());
});
// Return statement remains the same
return (
// ... your JSX here, unchanged
);
};
```
:::
Why this works:
1. `ReactiveVar` bridges the systems: When you toggle `hideCompleted` (Solid signal), the `createEffect` updates the `ReactiveVar`. This invalidates and re-runs the Tracker.autorun, which re-fetches tasks with the updated query.
2. No major rewrites: Your existing signals and UI logic stay intact.
3. Performance: Tracker handles the re-fetch efficiently, and Solid updates the UI via the `tasks` signal.
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step06-all.png"/>
<img width="200px" src="/tutorials/solid/assets/step06-filtered.png"/>
In the next step we are going to include user access in your app.

View File

@@ -0,0 +1,414 @@
## 7: Adding User Accounts
### 7.1: Password Authentication
Meteor already comes with a basic authentication and account management system out of the box, so you only need to add the `accounts-password` to enable username and password authentication:
```shell
meteor add accounts-password
```
> There are many more authentication methods supported. You can read more about the accounts system [here](https://v3-docs.meteor.com/api/accounts.html).
We also recommend you to install `bcrypt` node module, otherwise, you are going to see a warning saying that you are using a pure-Javascript implementation of it.
```shell
meteor npm install --save bcrypt
```
> You should always use `meteor npm` instead of only `npm` so you always use the `npm` version pinned by Meteor, this helps you to avoid problems due to different versions of npm installing different modules.
### 7.2: Create User Account
Now you can create a default user for our app, we are going to use `meteorite` as username, we just create a new user on server startup if we didn't find it in the database.
::: code-group
```js [server/main.js]
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base'; // [!code highlight]
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksPublications";
import "../imports/api/TasksMethods";
const SEED_USERNAME = 'meteorite'; // [!code highlight]
const SEED_PASSWORD = 'password'; // [!code highlight]
Meteor.startup(async () => {
if (!(await Accounts.findUserByUsername(SEED_USERNAME))) { // [!code highlight]
await Accounts.createUser({ // [!code highlight]
username: SEED_USERNAME, // [!code highlight]
password: SEED_PASSWORD, // [!code highlight]
}); // [!code highlight]
} // [!code highlight]
...
});
```
:::
You should not see anything different in your app UI yet.
### 7.3: Login Form
You need to provide a way for the users to input the credentials and authenticate, for that we need a form.
Our login form will be simple, with just two fields (username and password) and a button. You should use `Meteor.loginWithPassword(username, password)`; to authenticate your user with the provided inputs.
Create a new component `Login.jsx` in `imports/ui/`:
::: code-group
```jsx [imports/ui/Login.jsx]
import { createSignal } from "solid-js";
import { Meteor } from "meteor/meteor";
export const Login = () => {
const [username, setUsername] = createSignal('');
const [password, setPassword] = createSignal('');
const login = async (event) => {
event.preventDefault();
await Meteor.loginWithPassword(username(), password());
};
return (
<form class="login-form" onSubmit={login}>
<div>
<label for="username">Username</label>
<input
type="text"
placeholder="Username"
name="username"
required
value={username()}
onInput={(e) => setUsername(e.currentTarget.value)}
/>
</div>
<div>
<label for="password">Password</label>
<input
type="password"
placeholder="Password"
name="password"
required
value={password()}
onInput={(e) => setPassword(e.currentTarget.value)}
/>
</div>
<div>
<button type="submit">Log In</button>
</div>
</form>
);
};
```
:::
Be sure also to import the login form in `App.jsx`.
::: code-group
```jsx [imports/ui/App.jsx]
import { ReactiveVar } from 'meteor/reactive-var';
import { createSignal, For, Show, createEffect } from "solid-js";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { TasksCollection } from "../api/TasksCollection";
import { Task } from "./Task.jsx";
import { Login } from "./Login.jsx"; // [!code highlight]
// ... rest of the script
```
:::
Ok, now you have a form, let's use it.
### 7.4: Require Authentication
Our app should only allow an authenticated user to access its task management features.
We can accomplish that by rendering the `Login` component when we dont have an authenticated user. Otherwise, we render the form, filter, and list.
To achieve this, we will use a conditional `<Show>` in `App.jsx`:
::: code-group
```jsx [imports/ui/App.jsx]
// ... other imports and code
const [currentUser, setCurrentUser] = createSignal(Meteor.user()); // Reactive current user // [!code highlight]
Tracker.autorun(() => { // [!code highlight]
setCurrentUser(Meteor.user()); // [!code highlight]
}); // [!code highlight]
// ... rest of script
return (
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ To Do List {incompleteCount() > 0 ? `(${incompleteCount()})` : ''}</h1>
</div>
</div>
</header>
<div class="main">
<Show // [!code highlight]
when={currentUser()} // [!code highlight]
fallback={<Login />} // [!code highlight]
> // [!code highlight]
<form class="task-form" onSubmit={addTask}>
<input
type="text"
placeholder="Type to add new tasks"
value={newTask()}
onInput={(e) => setNewTask(e.currentTarget.value)}
/>
<button type="submit">Add Task</button>
</form>
<div class="filter">
<button onClick={toggleHideCompleted}>
<Show
when={hideCompleted()}
fallback="Hide Completed"
>
Show All
</Show>
</button>
</div>
<Show
when={isReady()}
fallback={<div>Loading ...</div>}
>
<ul class="tasks">
<For each={tasks()}>
{(task) => (
<Task task={task} />
)}
</For>
</ul>
</Show>
</Show> // [!code highlight]
</div>
</div>
);
```
:::
As you can see, if the user is logged in, we render the whole app (`currentUser` is truthy). Otherwise, we render the Login component.
### 7.5: Login Form style
Ok, let's style the login form now:
::: code-group
```css [imports/ui/main.css]
.login-form {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
align-items: center;
}
.login-form > div {
margin: 8px;
}
.login-form > div > label {
font-weight: bold;
}
.login-form > div > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
margin-top: 4px;
}
.login-form > div > input:focus {
outline: 0;
}
.login-form > div > button {
background-color: #62807e;
}
```
:::
Now your login form should be centralized and beautiful.
### 7.6: Server startup
Every task should have an owner from now on. So go to your database, as you learned before, and remove all the tasks from there:
`db.tasks.remove({});`
Change your `server/main.js` to add the seed tasks using your `meteorite` user as owner.
Make sure you restart the server after this change so `Meteor.startup` block will run again. This is probably going to happen automatically anyway as you are going to make changes in the server side code.
::: code-group
```js [server/main.js]
...
const user = await Accounts.findUserByUsername(SEED_USERNAME);
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", {
text: taskName,
createdAt: new Date(),
userId: user._id
});
});
}
...
```
:::
See that we are using a new field called `userId` with our user `_id` field, we are also setting `createdAt` field.
### 7.7: Task owner
First, let's change our publication to publish the tasks only for the currently logged user. This is important for security, as you send only data that belongs to that user.
::: code-group
```js [/imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
let result = this.ready();
const userId = this.userId;
if (userId) {
result = TasksCollection.find({ userId });
}
return result;
});
```
:::
Now let's check if we have a `currentUser` before trying to fetch any data. Update the reactive `tasks` and `incompleteCount` to only run if logged in:
::: code-group
```jsx [imports/ui/App.jsx]
// ... other imports and code
Tracker.autorun(async () => {
setIsReady(subscription.ready());
if (!Meteor.userId()) { // [!code highlight] // Skip if not logged in
setTasks([]); // [!code highlight]
return; // [!code highlight]
} // [!code highlight]
// Use ReactiveVar in the query for Tracker reactivity
const query = hideCompletedVar.get() ? { isChecked: { $ne: true } } : {};
setTasks(await TasksCollection.find(query, { sort: { createdAt: -1, _id: -1 } }).fetchAsync());
});
// Reactive incomplete count
const [incompleteCount, setIncompleteCount] = createSignal(0);
Tracker.autorun(async () => {
if (!Meteor.userId()) { // [!code highlight] // Skip if not logged in
setIncompleteCount(0); // [!code highlight]
return; // [!code highlight]
} // [!code highlight]
setIncompleteCount(await TasksCollection.find({ isChecked: { $ne: true } }).countAsync());
});
// ... rest of component
```
:::
Also, update the `tasks.insert` method to include the field `userId` when creating a new task:
::: code-group
```js [imports/api/TasksMethods.js]
...
Meteor.methods({
"tasks.insert"(doc) {
const insertDoc = { ...doc };
if (!('userId' in insertDoc)) {
insertDoc.userId = this.userId;
}
return TasksCollection.insertAsync(insertDoc);
},
...
```
:::
### 7.8: Log out
We can also organize our tasks by showing the owners username below our app bar. Lets add a new `div` where the user can click and log out from the app:
::: code-group
```jsx [imports/ui/App.jsx]
...
<div class="main">
<Show
when={currentUser()}
fallback={<Login />}
>
<div class="user" onClick={() => Meteor.logout()}> // [!code highlight]
{currentUser()?.username} 🚪 // [!code highlight]
</div> // [!code highlight]
...
```
:::
Remember to style your username as well.
::: code-group
```css [imports/ui/main.css]
.user {
display: flex;
align-self: flex-end;
margin: 8px 16px 0;
font-weight: bold;
cursor: pointer;
}
```
:::
Phew! You have done quite a lot in this step. Authenticated the user, set the user in the tasks, and provided a way for the user to log out.
Your app should look like this:
<img width="200px" src="/tutorials/solid/assets/step07-login.png"/>
<img width="200px" src="/tutorials/solid/assets/step07-logout.png"/>
In the next step, we are going to learn how to deploy your app!

View File

@@ -0,0 +1,98 @@
## 8: Deploying
Deploying a Meteor application is similar to deploying any other Node.js app that uses websockets. You can find deployment options in [our guide](https://guide.meteor.com/deployment), including Meteor Up, Docker, and our recommended method, Galaxy.
In this tutorial, we will deploy our app on [Galaxy](https://galaxycloud.app/), which is our own cloud solution. Galaxy offers a free plan, so you can deploy and test your app. Pretty cool, right?
### 8.1: Create your account
You need a Meteor account to deploy your apps. If you dont have one yet, you can [sign up here](https://cloud.meteor.com/?isSignUp=true).
With this account, you can access our package manager, [Atmosphere](https://atmospherejs.com/), [Forums](https://forums.meteor.com/) and more.
### 8.2: Set up MongoDB (Optional)
As your app uses MongoDB the first step is to set up a MongoDB database, Galaxy offers MongoDB hosting on a free plan for testing purposes, and you can also request for a production ready database that allows you to scale.
In any MongoDB provider you will have a MongoDB URL which you must use. If you use the free option provided by Galaxy, the initial setup is done for you.
Galaxy MongoDB URL will be like this: `mongodb://username:<password>@org-dbname-01.mongodb.galaxy-cloud.io` .
> You can read more about Galaxy MongoDB [here](https://galaxy-support.meteor.com/en/article/mongodb-general-1syd5af/).
### 8.3: Set up settings
If you are not using the free option, then you need to create a settings file. Its a JSON file that Meteor apps can read configurations from. Create this file in a new folder called `private` in the root of your project. It is important to notice that `private` is a special folder that is not going to be published to the client side of your app.
Make sure you replace `Your MongoDB URL` by your own MongoDB URL :)
::: code-group
```json [private/settings.json]
{
"galaxy.meteor.com": {
"env": {
"MONGO_URL": "Your MongoDB URL"
}
}
}
```
:::
### 8.4: Deploy it
Now you are ready to deploy, run `meteor npm install` before deploying to make sure all your dependencies are installed.
You also need to choose a subdomain to publish your app. We are going to use the main domain `meteorapp.com` that is free and included on any Galaxy plan.
In this example we are going to use `solid-meteor-3.meteorapp.com` but make sure you select a different one, otherwise you are going to receive an error.
> You can learn how to use custom domains on Galaxy [here](https://galaxy-support.meteor.com/en/article/domains-16cijgc/). Custom domains are available starting with the Essentials plan.
Run the deployment command:
```shell
meteor deploy solid-meteor-3.meteorapp.com --free --mongo
```
> If you are not using the free hosting with MongoDB on Galaxy, then remove the `--mongo` flag from the deploy script and add `--settings private/settings.json` with the proper setting for your app.
Make sure you replace `solid-meteor-3` by a custom name that you want as subdomain. You will see a log like this:
```shell
meteor deploy solid-meteor-3.meteorapp.com --settings private/settings.json
Talking to Galaxy servers at https://us-east-1.galaxy-deploy.meteor.com
Preparing to build your app...
Preparing to upload your app...
Uploaded app bundle for new app at solid-meteor-3.meteorapp.com.
Galaxy is building the app into a native image.
Waiting for deployment updates from Galaxy...
Building app image...
Deploying app...
You have successfully deployed the first version of your app.
For details, visit https://galaxy.meteor.com/app/solid-meteor-3.meteorapp.com
```
This process usually takes just a few minutes, but it depends on your internet speed as its going to send your app bundle to Galaxy servers.
> Galaxy builds a new Docker image that contains your app bundle and then deploy containers using it, [read more](https://galaxy-support.meteor.com/en/article/container-environment-lfd6kh/).
You can check your logs on Galaxy, including the part that Galaxy is building your Docker image and deploying it.
### 8.5: Access the app and enjoy
Now you should be able to access your Galaxy dashboard at `https://galaxy.meteor.com/app/solid-meteor-3.meteorapp.com`.
You can also access your app on Galaxy 2.0 which is currently in beta at `https://galaxy-beta.meteor.com/<your-username>/us-east-1/apps/<your-app-name>.meteorapp.com`. Remember to use your own subdomain instead of `solid-meteor-3`.
You can access the app at [solid-meteor-3.meteorapp.com](https://solid-meteor-3.meteorapp.com/)! Just use your subdomain to access yours!
> We deployed to Galaxy running in the US (us-east-1), we also have Galaxy running in other regions in the world, check the list [here](https://galaxy-support.meteor.com/en/article/regions-1vucejm/).
This is huge, you have your app running on Galaxy, ready to be used by anyone in the world!

View File

@@ -0,0 +1,17 @@
## 9: Next Steps
You have completed the tutorial!
By now, you should have a good understanding of working with Meteor and Solid.
::: info
You can find the final version of this app in our [GitHub repository](https://github.com/meteor/meteor3-solid).
:::
Here are some options for what you can do next:
- Check out the complete [documentation](https://v3-docs.meteor.com/) to learn more about Meteor 3.
- Read the [Galaxy Guide](https://galaxy-support.meteor.com/en/article/deploy-to-galaxy-18gd6e2/) to learn more about deploying your app.
- Join our community on the [Meteor Forums](https://forums.meteor.com/) and the [Meteor Lounge on Discord](https://discord.gg/hZkTCaVjmT) to ask questions and share your experiences.
We can't wait to see what you build next!

Binary file not shown.

After

Width:  |  Height:  |  Size: 218 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 217 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

View File

@@ -0,0 +1,25 @@
# Meteor.js 3 + Solid
In this tutorial, we will create a simple To-Do app using [Solid](https://www.solidjs.com/) and Meteor 3.0. Meteor works well with other frameworks like [React](https://react.dev/), [Vue 3](https://vuejs.org/), [Svelte](https://svelte.dev/), and [Blaze](https://www.blazejs.org/).
Solid is a modern UI framework that compiles your reactive code to highly efficient DOM updates at runtime, resulting in smaller bundles and exceptional performance without a virtual DOM. Launched in 2020, it has gained popularity for its fine-grained reactivity, simplicity, and lightweight nature. Compared to older approaches, Solid eliminates much of the boilerplate and runtime overhead found in frameworks like React by using a compiler that optimizes updates precisely where needed. It employs a declarative JSX syntax with built-in primitives like signals for state management, effects, and resources that can be seamlessly integrated with Meteor's reactive data sources like[Tracker](https://docs.meteor.com/api/tracker.html) and [Minimongo](https://docs.meteor.com/api/collections.html). This means your UI updates automatically as data changes, without manual DOM manipulation.
If you're new and not sure what UI framework to use, Solid is a great place to start—it's easy to learn (especially if you're familiar with React-like JSX), highly performant with fine-grained reactivity, and has a growing community. You can still leverage Meteor packages designed for other frameworks, like [accounts-ui](https://docs.meteor.com/packages/accounts-ui), even in a Solid app.
To start building your Solid app, you'll need a code editor. If you're unsure which one to choose, [Visual Studio Code](https://code.visualstudio.com/) is a good option.
Lets begin building your app!
# Table of Contents
[[toc]]
<!-- @include: ./1.creating-the-app.md-->
<!-- @include: ./2.collections.md-->
<!-- @include: ./3.forms-and-events.md-->
<!-- @include: ./4.update-and-remove.md-->
<!-- @include: ./5.styles.md-->
<!-- @include: ./6.filter-tasks.md-->
<!-- @include: ./7.adding-user-accounts.md-->
<!-- @include: ./8.deploying.md-->
<!-- @include: ./9.next-steps.md-->

View File

@@ -0,0 +1,183 @@
## 1: Creating the app
### 1.1: Install Meteor
First, we need to install Meteor by following this [installation guide](https://docs.meteor.com/about/install.html).
### 1.2: Create Meteor Project
The easiest way to setup Meteor with Svelte is by using the command `meteor create` with the option `--svelte` and your project name:
```shell
meteor create --svelte simple-todos-svelte
```
Meteor will create all the necessary files for you.
The files located in the `client` directory are setting up your client side (web), you can see for example `client/main.html` where Meteor is rendering your App main component into the HTML.
Also, check the `server` directory where Meteor is setting up the server side (Node.js), you can see the `server/main.js` which would be a good place to initialize your MongoDB database with some data. You don't need to install MongoDB as Meteor provides an embedded version of it ready for you to use.
You can now run your Meteor app using:
```shell
meteor
```
Don't worry, Meteor will keep your app in sync with all your changes from now on.
Take a quick look at all the files created by Meteor, you don't need to understand them now but it's good to know where they are.
Your Svelte code will be located inside the `imports/ui` directory, and the `App.svelte` file will be the root component of your Svelte To-do app.
### 1.3: Create Tasks
To start working on our todo list app, lets replace the code of the default starter app with the code below. From there, well talk about what it does.
First, lets simplify our HTML entry point like so:
::: code-group
```html [client/main.html]
<head>
<title>Simple todo</title>
</head>
<body>
<div id="app"></div>
</body>
```
:::
The `client/main.js` file should import and render the main Svelte component:
::: code-group
```js [client/main.js]
import { Meteor } from 'meteor/meteor';
import App from '../imports/ui/App.svelte';
Meteor.startup(() => {
new App({
target: document.getElementById('app')
});
});
```
:::
Inside the `imports/ui` folder let us modify `App.svelte` to display a header and a list of tasks:
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
let tasks = [
{ text: 'This is task 1' },
{ text: 'This is task 2' },
{ text: 'This is task 3' },
];
</script>
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<ul>
{#each tasks as task (task.text)}
<li>{task.text}</li>
{/each}
</ul>
</div>
```
:::
We just modified our main Svelte component `App.svelte`, which will be rendered into the `#app` div in the body. It shows a header and a list of tasks. For now, we're using static sample data to display the tasks.
### 1.4: View Sample Tasks
As you are not connecting to your server and database yet, weve defined some sample data directly in `App.svelte` to render a list of tasks.
At this point meteor should be running on port 3000 so you can visit the running app and see your list with three tasks displayed at [http://localhost:3000/](http://localhost:3000/) - but if meteor is not running, go to your terminal and move to the top directory of your project and type `meteor` then press return to launch the app.
All right! Lets find out what all these bits of code are doing!
### 1.5: Rendering Data
<img width="688px" src="/tutorials/svelte/assets/mermaid-diagram-svelte-rendering.png"/>
In Svelte with Meteor, your main entry point is `client/main.js`, which imports and mounts your root Svelte component `App.svelte` to a target element in the HTML like `<div id="app"></div>`
Svelte components are defined in `.svelte` files, which can include `<script>`, `<style>`, and HTML markup. The HTML markup can use Svelte's templating syntax, such as <span v-pre>{#each}</span>
for looping and <span v-pre>{expression}</span> for interpolating data.
You can define reactive data and logic in the `<script>`
tag. In the code above, we defined a `tasks` array directly in the component. Inside the markup, we use
<span v-pre>{#each tasks as task}</span> to iterate over the array and display each task's `text`
property using <span v-pre>{task.text}</span>
For Meteor-specific reactivity (like subscriptions and collections), Svelte in Meteor uses special syntax like `$m:` for reactive statements that integrate with Meteor's Tracker. We'll cover that in later steps.
### 1.6: Mobile Look
Lets see how your app is looking on mobile. You can simulate a mobile environment by `right clicking` your app in the browser (we are assuming you are using Google Chrome, as it is the most popular browser) and then `inspect`, this will open a new window inside your browser called `Dev Tools`. In the `Dev Tools` you have a small icon showing a Mobile device and a Tablet:
<img width="500px" src="/tutorials/svelte/assets/step01-dev-tools-mobile-toggle.png"/>
Click on it and then select the phone that you want to simulate and in the top nav bar.
> You can also check your app in your personal cellphone. To do so, connect to your App using your local IP in the navigation browser of your mobile browser.
>
> This command should print your local IP for you on Unix systems
> `ifconfig | grep "inet " | grep -Fv 127.0.0.1 | awk '{print $2}'`
>
> On Microsoft Windows try this in a command prompt
> `ipconfig | findstr "IPv4 Address"`
You should see the following:
<img width="200px" src="/tutorials/svelte/assets/step01-mobile-without-meta-tags.png"/>
As you can see, everything is small, as we are not adjusting the view port for mobile devices. You can fix this and other similar issues by adding these lines to your `client/main.html` file, inside the `head` tag, after the `title`.
::: code-group
```html [client/main.html]
...
<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"/>
...
```
:::
Now your app should scale properly on mobile devices and look like this:
<img width="200px" src="/tutorials/svelte/assets/step01-mobile-with-meta-tags.png"/>
### 1.7: Hot Module Replacement
Meteor uses a package called [hot-module-replacement](https://docs.meteor.com/packages/hot-module-replacement) which is already added for you. This package updates the javascript modules in a running app that were modified during a rebuild. Reduces the feedback cycle while developing, so you can view and test changes quicker (it even updates the app before the build has finished). You are also not going to lose the state, your app code will be updated, and your state will be the same.
By default, when using Svelte with Meteor, reactivity is handled by packages like `zodern:melte` (which integrates Svelte with Meteor). This allows real-time updates of the users screen as data changes in the database without them having to manually refresh. You can read more about it [here](https://atmospherejs.com/zodern/melte).
> You can read more about packages [here](https://docs.meteor.com/packages/).
You should also add the package [dev-error-overlay](https://atmospherejs.com/meteor/dev-error-overlay) at this point, so you can see the errors in your web browser.
```shell
meteor add dev-error-overlay
```
You can try to make some mistakes and then you are going to see the errors in the browser and not only in the console.
In the next step we are going to work with our MongoDB database to be able to store our tasks.

View File

@@ -0,0 +1,171 @@
## 2: Collections
Meteor already sets up MongoDB for you. In order to use our database, we need to create a _collection_, which is where we will store our _documents_, in our case our `tasks`.
> You can read more about collections [here](https://v3-docs.meteor.com/api/collections.html).
In this step we will implement all the necessary code to have a basic collection for our tasks up and running.
### 2.1: Create Tasks Collection
We can create a new collection to store our tasks by creating a new file at `imports/api/TasksCollection.js` which instantiates a new Mongo collection and exports it.
::: code-group
```js [imports/api/TasksCollection.js]
import { Mongo } from "meteor/mongo";
export const TasksCollection = new Mongo.Collection("tasks");
```
:::
Notice that we stored the file in the `imports/api` directory, which is a place to store API-related code, like publications and methods. You can name this folder as you want, this is just a choice.
If there is a `imports/api/links.js` file from the starter project, you can delete that now as we don't need it.
> You can read more about app structure and imports/exports [here](http://guide.meteor.com/structure.html).
### 2.2: Initialize Tasks Collection
For our collection to work, you need to import it in the server so it sets some plumbing up.
You can either use `import "/imports/api/TasksCollection"` or `import { TasksCollection } from "/imports/api/TasksCollection"` if you are going to use on the same file, but make sure it is imported.
Now it is easy to check if there is data or not in our collection, otherwise, we can insert some sample data easily as well.
You don't need to keep the old content of `server/main.js`.
::: code-group
```js [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
const insertTask = async (taskText) =>
await TasksCollection.insertAsync({ text: taskText });
Meteor.startup(async () => {
if (await TasksCollection.find().countAsync() === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach(insertTask);
}
});
```
:::
So you are importing the `TasksCollection` and adding a few tasks to it iterating over an array of strings and for each string calling a function to insert this string as our `text` field in our `task` document.
### 2.3: Render Tasks Collection
Now comes the fun part, you will render the tasks with Svelte. That will be pretty simple.
In your `App.svelte` file, import the `TasksCollection` file and, instead of returning a static array, return the tasks saved in the database:
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: tasks = TasksCollection.find().fetch();
</script>
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<ul>
{#if subIsReady}
{#each tasks as task (task._id)}
<li>{task.text}</li>
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
</div>
```
:::
But wait! Something is missing. If you run your app now, you'll see that you don't render any tasks.
That's because we need to publish our data to the client.
> For more information on Publications/Subscriptions, please check our [docs](https://v3-docs.meteor.com/api/meteor.html#pubsub).
Meteor doesn't need REST calls. It instead relies on synchronizing the MongoDB on the server with a MiniMongoDB on the client. It does this by first publishing collections on the server and then subscribing to them on the client.
First, create a publication for our tasks:
::: code-group
```javascript [imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
return TasksCollection.find();
});
```
:::
Now, we need to import this file in our server:
::: code-group
```js [server/main.js]
...
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksPublications"; // [!code highlight]
const insertTask = taskText => TasksCollection.insertAsync({ text: taskText });
...
```
:::
The only thing left is subscribe to this publication, which we've already added in `App.svelte` using:
::: code-group
```javascript [imports/ui/App.svelte]
...
$m: handle = Meteor.subscribe("tasks");
...
```
:::
See how your app should look like now:
<img width="200px" src="/tutorials/svelte/assets/collections-tasks-list.png"/>
You can change your data on MongoDB in the server and your app will react and re-render for you.
You can connect to your MongoDB running `meteor mongo` in the terminal from your app folder or using a Mongo UI client, like [NoSQLBooster](https://nosqlbooster.com/downloads). Your embedded MongoDB is running in port `3001`.
See how to connect:
<img width="500px" src="/tutorials/svelte/assets/collections-connect-db.png"/>
See your database:
<img width="500px" src="/tutorials/svelte/assets/collections-see-database.png"/>
You can double-click your collection to see the documents stored on it:
<img width="500px" src="/tutorials/svelte/assets/collections-documents.png"/>
In the next step, we are going to create tasks using a form.

View File

@@ -0,0 +1,221 @@
## 3: Forms and Events
All apps need to allow the user to perform some sort of interaction with the data that is stored. In our case, the first type of interaction is to insert new tasks. Without it, our To-Do app wouldn't be very helpful.
One of the main ways in which a user can insert or edit data on a website is through forms. In most cases, it is a good idea to use the `<form>` tag since it gives semantic meaning to the elements inside it.
### 3.1: Create Task Form
Create a new `form` inside the `App.svelte` file, and inside well add an input field and a button. Place it between the `header` and the `ul`:
::: code-group
```html [imports/ui/App.svelte]
...
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
...
```
:::
Let's now add an `addTask()` function handler inside the script tags below the imports. It will call a Meteor method `tasks.insert` that isn't yet created but we'll soon make:
::: code-group
```html [imports/ui/App.svelte]
...
let newTask = '';
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
...
```
:::
Altogether, our file should look like:
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
let newTask = '';
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: tasks = TasksCollection.find().fetch();
</script>
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
<ul>
{#if subIsReady}
{#each tasks as task (task._id)}
<li>{task.text}</li>
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
</div>
```
:::
In the code above, we've integrated the form directly into the `App.svelte`
component, positioning it above the task list. We're using Svelte's `bind:value`
for two-way binding on the input and an `on:submit` handler for form submission.
### 3.2: Update the Stylesheet
You also can style it as you wish. For now, we only need some margin at the top so the form doesn't seem off the mark. Add the CSS class `.task-form`, this needs to be the same name in your `class` attribute in the form element.
::: code-group
```css [client/main.css]
...
.task-form {
margin-top: 1rem;
}
...
```
:::
### 3.3: Add Submit Handler
Now let's create a function to handle the form submit and insert a new task into the database. To do it, we will need to implement a Meteor Method.
Methods are essentially RPC calls to the server that let you perform operations on the server side securely. You can read more about Meteor Methods [here](https://guide.meteor.com/methods.html).
To create your methods, you can create a file called `TasksMethods.js`.
::: code-group
```javascript [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
"tasks.insert"(doc) {
return TasksCollection.insertAsync(doc);
},
});
```
:::
Remember to import your method on the `main.js` server file, delete the `insertTask` function, and invoke the new meteor method inside the `forEach` block.
::: code-group
```javascript [server/main.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "/imports/api/TasksCollection";
import "../imports/api/TasksPublications";
import "../imports/api/TasksMethods"; // [!code highlight]
Meteor.startup(async () => {
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", { // [!code highlight]
text: taskName, // [!code highlight]
createdAt: new Date(), // [!code highlight]
});
});
}
});
```
:::
Inside the `forEach` function, we are adding a task to the `tasks` collection by calling `Meteor.callAsync()`. The first argument is the name of the method we want to call, and the second argument is the text of the task.
Also, insert a date `createdAt` in your `task` document so you know when each task was created.
Now we need to import `TasksMethods.js` and add a listener to the `submit` event on the form:
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods"; // this import allows for optimistic execution // [!code highlight]
// ... rest of the script remains the same
</script>
<!-- markup remains the same -->
```
:::
In the `addTask` function (shown in 3.1), we prevent the default form submission, get the input value, call the Meteor method to insert the task optimistically, and clear the input.
Meteor methods execute optimistically on the client using MiniMongo while simultaneously calling the server. If the server call fails, MiniMongo rolls back the change, providing a speedy user experience. It's a bit like [rollback netcode](https://glossary.infil.net/?t=Rollback%20Netcode) in fighting video games.
### 3.4: Show Newest Tasks First
Now you just need to make a change that will make users happy: we need to show the newest tasks first. We can accomplish this quite quickly by sorting our [Mongo](https://guide.meteor.com/collections.html#mongo-collections) query.
::: code-group
```html [imports/ui/App.svelte]
<script>
// ... other imports and code
$m: tasks = TasksCollection.find({}, { sort: { createdAt: -1 } }).fetch(); // [!code highlight]
</script>
<!-- markup remains the same -->
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step03-form-new-task.png"/>
<img width="200px" src="/tutorials/svelte/assets/step03-new-task-on-list.png"/>
In the next step, we are going to update your tasks state and provide a way for users to remove tasks.

View File

@@ -0,0 +1,197 @@
## 4: Update and Remove
Up until now, you have only inserted documents into our collection. Let's take a look at how you can update and remove them by interacting with the user interface.
### 4.1: Add Checkbox
First, you need to add a `checkbox` element to your `Task` component.
Next, lets create a new file for our `task` template in `imports/ui/Task.svelte`, so we can start to separate the logic in our app.
::: code-group
```html [imports/ui/Task.svelte]
<script>
import { Meteor } from "meteor/meteor";
import "/imports/api/TasksMethods"; // Import for optimistic UI
export let task;
async function toggleChecked() {
await Meteor.callAsync("tasks.toggleChecked", { _id: task._id, isChecked: task.isChecked });
}
</script>
<li>
<label>
<input type="checkbox" checked={task.isChecked} on:change={toggleChecked} />
<span>{task.text}</span>
</label>
</li>
```
:::
Now, update `App.svelte` to import and use the `Task` component in the <span v-pre>{#each}</span> loop. Remove the old `<li>` markup.
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods";
import Task from "./Task.svelte"; // [!code highlight]
let newTask = '';
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: tasks = TasksCollection.find({}, { sort: { createdAt: -1 } }).fetch();
</script>
<div class="container">
<header>
<h1>Todo List</h1>
</header>
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
<ul>
{#if subIsReady}
{#each tasks as task (task._id)}
<Task {task} /> <!-- // [!code highlight] -->
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
</div>
```
:::
### 4.2: Toggle Checkbox
Now you can update your task document by toggling its `isChecked` field.
First, create a new method called `tasks.toggleChecked` to update the `isChecked` property.
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
...
"tasks.toggleChecked"({ _id, isChecked }) {
return TasksCollection.updateAsync(_id, {
$set: { isChecked: !isChecked },
});
},
});
```
:::
In `Task.svelte` (as shown above), we've added an `on:change` handler that calls the method to toggle the checked state.
Toggling checkboxes should now persist in the DB even if you refresh the web browser.
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step04-checkbox.png"/>
If your computer is fast enough, it's possible that when it sets up the default tasks a few will have the same date. That will cause them to non-deterministically "jump around" in the UI as you toggle checkboxes and the UI reactively updates. To make it stable, you can add a secondary sort on the `_id` of the task:
::: code-group
```html [imports/ui/App.svelte]
<script>
// ... other code
$m: tasks = TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetch(); // [!code highlight]
</script>
<!-- markup remains the same -->
```
:::
### 4.3: Remove tasks
You can remove tasks with just a few lines of code.
First, add a button after the `label` in your `Task` component and a `deleteTask` function between the `script` tags.
::: code-group
```html [imports/ui/Task.svelte]
<script>
import { Meteor } from "meteor/meteor";
import "/imports/api/TasksMethods";
export let task;
async function toggleChecked() {
await Meteor.callAsync("tasks.toggleChecked", { _id: task._id, isChecked: task.isChecked });
}
async function deleteTask() { // [!code highlight]
await Meteor.callAsync("tasks.delete", { _id: task._id }); // [!code highlight]
} // [!code highlight]
</script>
<li>
<label>
<input type="checkbox" checked={task.isChecked} on:change={toggleChecked} />
<span>{task.text}</span>
</label>
<button class="delete" on:click={deleteTask}>&times;</button> <!-- // [!code highlight] -->
</li>
```
:::
Next you need to have a function to delete the task. For that, let's create a new method called `tasks.delete`:
::: code-group
```js [imports/api/TasksMethods.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.methods({
...
"tasks.delete"({ _id }) {
return TasksCollection.removeAsync(_id);
},
});
```
:::
Now the removal logic is handled in `Task.svelte` via the `on:click` event on the delete button, which calls the Meteor method.
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step04-delete-button.png"/>
### 4.4: Getting data in event handlers
In a collection, every inserted document has a unique `_id` field that can refer to that specific document. Inside the component, the `task` prop provides access to the task object, including its `_id`
and other fields like `isChecked` and `text`. We use these to call Meteor methods for updating or removing the specific task.
In the next step, we are going to improve the look of your app using CSS with Flexbox.

View File

@@ -0,0 +1,215 @@
## 5: Styles
### 5.1: CSS
Our user interface up until this point has looked quite ugly. Let's add some basic styling which will serve as the foundation for a more professional looking app.
Replace the content of our `client/main.css` file with the one below, the idea is to have an app bar at the top, and a scrollable content including:
- form to add new tasks;
- list of tasks.
::: code-group
```css [client/main.css]
body {
font-family: sans-serif;
background-color: #315481;
background-image: linear-gradient(to bottom, #315481, #918e82 100%);
background-attachment: fixed;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
font-size: 14px;
}
button {
font-weight: bold;
font-size: 1em;
border: none;
color: white;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
padding: 5px;
cursor: pointer;
}
button:focus {
outline: 0;
}
.app {
display: flex;
flex-direction: column;
height: 100vh;
}
.app-header {
flex-grow: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.main {
display: flex;
flex-direction: column;
flex-grow: 1;
overflow: auto;
background: white;
}
.main::-webkit-scrollbar {
width: 0;
height: 0;
background: inherit;
}
header {
background: #d2edf4;
background-image: linear-gradient(to bottom, #d0edf5, #e1e5f0 100%);
padding: 20px 15px 15px 15px;
position: relative;
box-shadow: 0 3px 3px rgba(34, 25, 25, 0.4);
}
.app-bar {
display: flex;
justify-content: space-between;
}
.app-bar h1 {
font-size: 1.5em;
margin: 0;
display: inline-block;
margin-right: 1em;
}
.task-form {
display: flex;
margin: 16px;
}
.task-form > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
}
.task-form > input:focus {
outline: 0;
}
.task-form > button {
min-width: 100px;
height: 95%;
background-color: #315481;
}
.tasks {
list-style-type: none;
padding-inline-start: 0;
padding-left: 16px;
padding-right: 16px;
margin-block-start: 0;
margin-block-end: 0;
}
.tasks > li {
display: flex;
padding: 16px;
border-bottom: #eee solid 1px;
align-items: center;
}
.tasks > li > label {
flex-grow: 1;
}
.tasks > li > button {
justify-self: flex-end;
background-color: #ff3046;
}
```
:::
> If you want to learn more about this stylesheet check this article about [Flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/), and also this free [video tutorial](https://flexbox.io/) about it from [Wes Bos](https://twitter.com/wesbos).
>
> Flexbox is an excellent tool to distribute and align elements in your UI.
### 5.2: Applying styles
Now you need to add some elements around your components. You are going to add a `class` to your main `div` in the `App.svelte`, also a `header` element with a few `div` elements around your `h1`, and a main `div` around your form and list. Check below how it should be; pay attention to the name of the classes, they need to be the same as in the CSS file:
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods";
import Task from "./Task.svelte";
let newTask = '';
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: tasks = TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetch();
</script>
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ Todo List</h1>
</div>
</div>
</header>
<div class="main">
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
<ul class="tasks">
{#if subIsReady}
{#each tasks as task (task._id)}
<Task {task} />
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
</div>
</div>
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step05-styles.png"/>
In the next step, we are going to make this task list more interactive, for example, providing a way to filter tasks.

View File

@@ -0,0 +1,211 @@
## 6: Filter tasks
In this step, you will filter your tasks by status and show the number of pending tasks.
### 6.1: Reactive State
First, you will add a button to show or hide the completed tasks from the list.
In Svelte, we can manage component state using reactive variables directly in the `<script>` tag. Svelte's reactivity will automatically update the UI when the state changes.
We'll add a `hideCompleted` variable to the `App.svelte` component and a function to toggle it.
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods";
import Task from "./Task.svelte";
let newTask = '';
let hideCompleted = false; // [!code highlight]
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
function toggleHideCompleted() { // [!code highlight]
hideCompleted = !hideCompleted; // [!code highlight]
} // [!code highlight]
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: tasks = TasksCollection.find({}, { sort: { createdAt: -1, _id: -1 } }).fetch();
</script>
<!-- markup will be updated in next steps -->
```
:::
Then, add the button in the markup to toggle the state:
::: code-group
```html [imports/ui/App.svelte]
<!-- ... script remains the same -->
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ Todo List</h1>
</div>
</div>
</header>
<div class="main">
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
<div class="filter"> <!-- // [!code highlight] -->
<button on:click={toggleHideCompleted}> <!-- // [!code highlight] -->
{#if hideCompleted} <!-- // [!code highlight] -->
Show All <!-- // [!code highlight] -->
{:else} <!-- // [!code highlight] -->
Hide Completed <!-- // [!code highlight] -->
{/if} <!-- // [!code highlight] -->
</button> <!-- // [!code highlight] -->
</div> <!-- // [!code highlight] -->
<ul class="tasks">
{#if subIsReady}
{#each tasks as task (task._id)}
<Task {task} />
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
</div>
</div>
```
:::
You may notice were using <span v-pre>{#if}</span> (a conditional block) for the button text. You can learn more about Svelte's conditional rendering [here](https://svelte.dev/docs#client-side-component-api).
### 6.2: Button style
You should add some style to your button so it does not look gray and without a good contrast. You can use the styles below as a reference:
::: code-group
```css [client/main.css]
.filter {
display: flex;
justify-content: center;
}
.filter > button {
background-color: #62807e;
}
```
:::
### 6.3: Filter Tasks
Now, update the reactive tasks fetch to apply the filter if `hideCompleted` is true. We'll also add a reactive variable for the incomplete count.
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods";
import Task from "./Task.svelte";
let newTask = '';
let hideCompleted = false;
async function addTask(event) {
event.preventDefault();
if (newTask.trim()) {
await Meteor.callAsync("tasks.insert", {
text: newTask,
createdAt: new Date(),
});
newTask = '';
}
}
function toggleHideCompleted() {
hideCompleted = !hideCompleted;
}
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
// Reactive tasks with filter
$m: tasks = TasksCollection.find( // [!code highlight]
hideCompleted ? { isChecked: { $ne: true } } : {}, // [!code highlight]
{ sort: { createdAt: -1, _id: -1 } } // [!code highlight]
).fetch(); // [!code highlight]
// Reactive incomplete count // [!code highlight]
$m: incompleteCount = TasksCollection.find({ isChecked: { $ne: true } }).count(); // [!code highlight]
$m: incompleteDisplay = incompleteCount > 0 ? `(${incompleteCount})` : ''; // [!code highlight]
</script>
<!-- markup remains the same -->
```
:::
### 6.4: Meteor Dev Tools Extension
You can install an extension to visualize the data in your Mini Mongo.
[Meteor DevTools Evolved](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf) will help you to debug your app as you can see what data is on Mini Mongo.
<img width="800px" src="/tutorials/svelte/assets/step06-extension.png"/>
You can also see all the messages that Meteor is sending and receiving from the server, this is useful for you to learn more about how Meteor works.
<img width="800px" src="/tutorials/svelte/assets/step06-ddp-messages.png"/>
Install it in your Google Chrome browser using this [link](https://chrome.google.com/webstore/detail/meteor-devtools-evolved/ibniinmoafhgbifjojidlagmggecmpgf).
### 6.5: Pending tasks
Update the App component in order to show the number of pending tasks in the app bar.
You should avoid adding zero to your app bar when there are no pending tasks. Use the reactive `incompleteDisplay` in the header:
::: code-group
```html [imports/ui/App.svelte]
<!-- ... script with incompleteDisplay remains the same -->
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ To Do List {incompleteDisplay}</h1> <!-- // [!code highlight] -->
</div>
</div>
</header>
<!-- rest of markup -->
</div>
```
:::
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step06-all.png"/>
<img width="200px" src="/tutorials/svelte/assets/step06-filtered.png"/>
In the next step we are going to include user access in your app.

View File

@@ -0,0 +1,390 @@
## 7: Adding User Accounts
### 7.1: Password Authentication
Meteor already comes with a basic authentication and account management system out of the box, so you only need to add the `accounts-password` to enable username and password authentication:
```shell
meteor add accounts-password
```
> There are many more authentication methods supported. You can read more about the accounts system [here](https://v3-docs.meteor.com/api/accounts.html).
We also recommend you to install `bcrypt` node module, otherwise, you are going to see a warning saying that you are using a pure-Javascript implementation of it.
```shell
meteor npm install --save bcrypt
```
> You should always use `meteor npm` instead of only `npm` so you always use the `npm` version pinned by Meteor, this helps you to avoid problems due to different versions of npm installing different modules.
### 7.2: Create User Account
Now you can create a default user for our app, we are going to use `meteorite` as username, we just create a new user on server startup if we didn't find it in the database.
::: code-group
```js [server/main.js]
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base'; // [!code highlight]
import { TasksCollection } from '/imports/api/TasksCollection';
import "../imports/api/TasksPublications";
import "../imports/api/TasksMethods";
const SEED_USERNAME = 'meteorite'; // [!code highlight]
const SEED_PASSWORD = 'password'; // [!code highlight]
Meteor.startup(async () => {
if (!(await Accounts.findUserByUsername(SEED_USERNAME))) { // [!code highlight]
await Accounts.createUser({ // [!code highlight]
username: SEED_USERNAME, // [!code highlight]
password: SEED_PASSWORD, // [!code highlight]
}); // [!code highlight]
} // [!code highlight]
...
});
```
:::
You should not see anything different in your app UI yet.
### 7.3: Login Form
You need to provide a way for the users to input the credentials and authenticate, for that we need a form.
Our login form will be simple, with just two fields (username and password) and a button. You should use `Meteor.loginWithPassword(username, password)`; to authenticate your user with the provided inputs.
Create a new component `Login.svelte` in `imports/ui/`:
::: code-group
```html [imports/ui/Login.svelte]
<script>
import { Meteor } from 'meteor/meteor';
let username = '';
let password = '';
async function login(event) {
event.preventDefault();
await Meteor.loginWithPassword(username, password);
}
</script>
<form class="login-form" on:submit={login}>
<div>
<label for="username">Username</label>
<input
type="text"
placeholder="Username"
name="username"
required
bind:value={username}
/>
</div>
<div>
<label for="password">Password</label>
<input
type="password"
placeholder="Password"
name="password"
required
bind:value={password}
/>
</div>
<div>
<button type="submit">Log In</button>
</div>
</form>
```
:::
Be sure also to import the login form in `App.svelte`.
::: code-group
```html [imports/ui/App.svelte]
<script>
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "../api/TasksCollection";
import "/imports/api/TasksMethods";
import Task from "./Task.svelte";
import Login from "./Login.svelte"; // [!code highlight]
// ... rest of the script
</script>
<!-- markup will be updated in next steps -->
```
:::
Ok, now you have a form, let's use it.
### 7.4: Require Authentication
Our app should only allow an authenticated user to access its task management features.
We can accomplish that by rendering the `Login` component when we dont have an authenticated user. Otherwise, we render the form, filter, and list.
To achieve this, we will use a conditional block in `App.svelte`:
::: code-group
```html [imports/ui/App.svelte]
<script>
// ... other imports and code
$m: currentUser = Meteor.user(); // Reactive current user // [!code highlight]
</script>
<div class="app">
<header>
<div class="app-bar">
<div class="app-header">
<h1>📝️ To Do List {incompleteDisplay}</h1>
</div>
</div>
</header>
<div class="main">
{#if currentUser} <!-- // [!code highlight] -->
<form class="task-form" on:submit={addTask}>
<input type="text" placeholder="Type to add new tasks" bind:value={newTask} />
<button type="submit">Add Task</button>
</form>
<div class="filter">
<button on:click={toggleHideCompleted}>
{#if hideCompleted}
Show All
{:else}
Hide Completed
{/if}
</button>
</div>
<ul class="tasks">
{#if subIsReady}
{#each tasks as task (task._id)}
<Task {task} />
{/each}
{:else}
<div>Loading ...</div>
{/if}
</ul>
{:else} <!-- // [!code highlight] -->
<Login /> <!-- // [!code highlight] -->
{/if} <!-- // [!code highlight] -->
</div>
</div>
```
:::
As you can see, if the user is logged in, we render the whole app (`currentUser` is truthy). Otherwise, we render the Login component.
### 7.5: Login Form style
Ok, let's style the login form now:
::: code-group
```css [client/main.css]
.login-form {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
align-items: center;
}
.login-form > div {
margin: 8px;
}
.login-form > div > label {
font-weight: bold;
}
.login-form > div > input {
flex-grow: 1;
box-sizing: border-box;
padding: 10px 6px;
background: transparent;
border: 1px solid #aaa;
width: 100%;
font-size: 1em;
margin-right: 16px;
margin-top: 4px;
}
.login-form > div > input:focus {
outline: 0;
}
.login-form > div > button {
background-color: #62807e;
}
```
:::
Now your login form should be centralized and beautiful.
### 7.6: Server startup
Every task should have an owner from now on. So go to your database, as you learned before, and remove all the tasks from there:
`db.tasks.remove({});`
Change your `server/main.js` to add the seed tasks using your `meteorite` user as owner.
Make sure you restart the server after this change so `Meteor.startup` block will run again. This is probably going to happen automatically anyway as you are going to make changes in the server side code.
::: code-group
```js [server/main.js]
...
const user = await Accounts.findUserByUsername(SEED_USERNAME);
if ((await TasksCollection.find().countAsync()) === 0) {
[
"First Task",
"Second Task",
"Third Task",
"Fourth Task",
"Fifth Task",
"Sixth Task",
"Seventh Task",
].forEach((taskName) => {
Meteor.callAsync("tasks.insert", {
text: taskName,
createdAt: new Date(),
userId: user._id
});
});
}
...
```
:::
See that we are using a new field called `userId` with our user `_id` field, we are also setting `createdAt` field.
### 7.7: Task owner
First, let's change our publication to publish the tasks only for the currently logged user. This is important for security, as you send only data that belongs to that user.
::: code-group
```js [/imports/api/TasksPublications.js]
import { Meteor } from "meteor/meteor";
import { TasksCollection } from "./TasksCollection";
Meteor.publish("tasks", function () {
let result = this.ready();
const userId = this.userId;
if (userId) {
result = TasksCollection.find({ userId });
}
return result;
});
```
:::
Now let's check if we have a `currentUser` before trying to fetch any data. Update the reactive `tasks` and `incompleteCount` to only run if logged in:
::: code-group
```html [imports/ui/App.svelte]
<script>
// ... other imports and code
$m: handle = Meteor.subscribe("tasks");
$m: subIsReady = handle.ready();
$m: currentUser = Meteor.user(); // Reactive current user
$m: tasks = currentUser // [!code highlight]
? TasksCollection.find( // [!code highlight]
hideCompleted ? { isChecked: { $ne: true } } : {}, // [!code highlight]
{ sort: { createdAt: -1, _id: -1 } } // [!code highlight]
).fetch() // [!code highlight]
: []; // [!code highlight]
$: incompleteCount = currentUser // [!code highlight]
? TasksCollection.find({ isChecked: { $ne: true } }).count() // [!code highlight]
: 0; // [!code highlight]
$: incompleteDisplay = incompleteCount > 0 ? `(${incompleteCount})` : '';
</script>
<!-- markup remains the same -->
```
:::
Also, update the `tasks.insert` method to include the field `userId` when creating a new task:
::: code-group
```js [imports/api/TasksMethods.js]
...
Meteor.methods({
"tasks.insert"(doc) {
const insertDoc = { ...doc };
if (!('userId' in insertDoc)) {
insertDoc.userId = this.userId;
}
return TasksCollection.insertAsync(insertDoc);
},
...
```
:::
### 7.8: Log out
We can also organize our tasks by showing the owners username below our app bar. Lets add a new `div` where the user can click and log out from the app:
::: code-group
```html [imports/ui/App.svelte]
...
<div class="main">
{#if currentUser}
<div class="user" on:click={() => Meteor.logout()}> <!-- // [!code highlight] -->
{currentUser.username} 🚪 <!-- // [!code highlight] -->
</div> <!-- // [!code highlight] -->
...
```
:::
Remember to style your username as well.
::: code-group
```css [client/main.css]
.user {
display: flex;
align-self: flex-end;
margin: 8px 16px 0;
font-weight: bold;
cursor: pointer;
}
```
:::
Phew! You have done quite a lot in this step. Authenticated the user, set the user in the tasks, and provided a way for the user to log out.
Your app should look like this:
<img width="200px" src="/tutorials/svelte/assets/step07-login.png"/>
<img width="200px" src="/tutorials/svelte/assets/step07-logout.png"/>
In the next step, we are going to learn how to deploy your app!

View File

@@ -0,0 +1,98 @@
## 8: Deploying
Deploying a Meteor application is similar to deploying any other Node.js app that uses websockets. You can find deployment options in [our guide](https://guide.meteor.com/deployment), including Meteor Up, Docker, and our recommended method, Galaxy.
In this tutorial, we will deploy our app on [Galaxy](https://galaxycloud.app/), which is our own cloud solution. Galaxy offers a free plan, so you can deploy and test your app. Pretty cool, right?
### 8.1: Create your account
You need a Meteor account to deploy your apps. If you dont have one yet, you can [sign up here](https://cloud.meteor.com/?isSignUp=true).
With this account, you can access our package manager, [Atmosphere](https://atmospherejs.com/), [Forums](https://forums.meteor.com/) and more.
### 8.2: Set up MongoDB (Optional)
As your app uses MongoDB the first step is to set up a MongoDB database, Galaxy offers MongoDB hosting on a free plan for testing purposes, and you can also request for a production ready database that allows you to scale.
In any MongoDB provider you will have a MongoDB URL which you must use. If you use the free option provided by Galaxy, the initial setup is done for you.
Galaxy MongoDB URL will be like this: `mongodb://username:<password>@org-dbname-01.mongodb.galaxy-cloud.io` .
> You can read more about Galaxy MongoDB [here](https://galaxy-support.meteor.com/en/article/mongodb-general-1syd5af/).
### 8.3: Set up settings
If you are not using the free option, then you need to create a settings file. Its a JSON file that Meteor apps can read configurations from. Create this file in a new folder called `private` in the root of your project. It is important to notice that `private` is a special folder that is not going to be published to the client side of your app.
Make sure you replace `Your MongoDB URL` by your own MongoDB URL :)
::: code-group
```json [private/settings.json]
{
"galaxy.meteor.com": {
"env": {
"MONGO_URL": "Your MongoDB URL"
}
}
}
```
:::
### 8.4: Deploy it
Now you are ready to deploy, run `meteor npm install` before deploying to make sure all your dependencies are installed.
You also need to choose a subdomain to publish your app. We are going to use the main domain `meteorapp.com` that is free and included on any Galaxy plan.
In this example we are going to use `svelte-meteor-3.meteorapp.com` but make sure you select a different one, otherwise you are going to receive an error.
> You can learn how to use custom domains on Galaxy [here](https://galaxy-support.meteor.com/en/article/domains-16cijgc/). Custom domains are available starting with the Essentials plan.
Run the deployment command:
```shell
meteor deploy svelte-meteor-3.meteorapp.com --free --mongo
```
> If you are not using the free hosting with MongoDB on Galaxy, then remove the `--mongo` flag from the deploy script and add `--settings private/settings.json` with the proper setting for your app.
Make sure you replace `svelte-meteor-3` by a custom name that you want as subdomain. You will see a log like this:
```shell
meteor deploy svelte-meteor-3.meteorapp.com --settings private/settings.json
Talking to Galaxy servers at https://us-east-1.galaxy-deploy.meteor.com
Preparing to build your app...
Preparing to upload your app...
Uploaded app bundle for new app at svelte-meteor-3.meteorapp.com.
Galaxy is building the app into a native image.
Waiting for deployment updates from Galaxy...
Building app image...
Deploying app...
You have successfully deployed the first version of your app.
For details, visit https://galaxy.meteor.com/app/svelte-meteor-3.meteorapp.com
```
This process usually takes just a few minutes, but it depends on your internet speed as its going to send your app bundle to Galaxy servers.
> Galaxy builds a new Docker image that contains your app bundle and then deploy containers using it, [read more](https://galaxy-support.meteor.com/en/article/container-environment-lfd6kh/).
You can check your logs on Galaxy, including the part that Galaxy is building your Docker image and deploying it.
### 8.5: Access the app and enjoy
Now you should be able to access your Galaxy dashboard at `https://galaxy.meteor.com/app/svelte-meteor-3.meteorapp.com`.
You can also access your app on Galaxy 2.0 which is currently in beta at `https://galaxy-beta.meteor.com/<your-username>/us-east-1/apps/<your-app-name>.meteorapp.com`. Remember to use your own subdomain instead of `svelte-meteor-3`.
You can access the app at [svelte-meteor-3.meteorapp.com](https://svelte-meteor-3.meteorapp.com/)! Just use your subdomain to access yours!
> We deployed to Galaxy running in the US (us-east-1), we also have Galaxy running in other regions in the world, check the list [here](https://galaxy-support.meteor.com/en/article/regions-1vucejm/).
This is huge, you have your app running on Galaxy, ready to be used by anyone in the world!

View File

@@ -0,0 +1,17 @@
## 9: Next Steps
You have completed the tutorial!
By now, you should have a good understanding of working with Meteor and Svelte.
::: info
You can find the final version of this app in our [GitHub repository](https://github.com/meteor/meteor3-svelte).
:::
Here are some options for what you can do next:
- Check out the complete [documentation](https://v3-docs.meteor.com/) to learn more about Meteor 3.
- Read the [Galaxy Guide](https://galaxy-support.meteor.com/en/article/deploy-to-galaxy-18gd6e2/) to learn more about deploying your app.
- Join our community on the [Meteor Forums](https://forums.meteor.com/) and the [Meteor Lounge on Discord](https://discord.gg/hZkTCaVjmT) to ask questions and share your experiences.
We can't wait to see what you build next!

Binary file not shown.

After

Width:  |  Height:  |  Size: 218 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 16 KiB

Some files were not shown because too many files have changed in this diff Show More