<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bruno Galvao on Medium]]></title>
        <description><![CDATA[Stories by Bruno Galvao on Medium]]></description>
        <link>https://medium.com/@brunopgalvao?source=rss-ddc99afb7ece------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*teKR7RCQulDl43f6hEt2Xg.jpeg</url>
            <title>Stories by Bruno Galvao on Medium</title>
            <link>https://medium.com/@brunopgalvao?source=rss-ddc99afb7ece------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:59:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brunopgalvao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TON vs Satsuma: Sharding, Sub-Second Blocks and Finality]]></title>
            <link>https://medium.com/@brunopgalvao/ton-vs-satsuma-sharding-sub-second-blocks-and-finality-42bfb80051e7?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bfb80051e7</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 00:00:32 GMT</pubDate>
            <atom:updated>2026-07-11T11:38:09.017Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TON just shipped sub-second blocks and unbounded sharding. I measured Satsuma against it — and most of what makes TON fast, Satsuma is built not to need. Here’s the reasoning, and the one idea worth borrowing.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ospo-Eq8xwu37TGQAi4pg.png" /></figure><p>Earlier this year TON shipped Catchain 2.0: roughly 6× the block rate, sub-second “instant” transactions, and fees heading toward feeless. It’s a genuinely impressive piece of engineering, and it’s fair to ask the obvious question about a chain like ours: Satsuma runs 2-second blocks with finality in a few seconds — should we be chasing those numbers too?</p><p>I ran the comparison in depth. The short answer is the interesting part: <strong>TON and Satsuma are engineered for opposite goals, so “faster” and “bigger” aren’t the same as “better” — they’re only better <em>for a job</em>.</strong> Most of what makes TON fast is solving problems our use case doesn’t have. One idea is worth borrowing, and I’ll show exactly how to build it. But the throughput and the “instant” layer that everyone quotes? I measured what they’d cost us, and we’re choosing not to pay — on purpose.</p><h3>The one-screen version</h3><ul><li><strong>Block time</strong> — TON ~400 ms · Satsuma 2 s (a config parameter, not a floor)</li><li><strong>“Instant” UX</strong> — TON 30–100 ms optimistic push · Satsuma none today (could add)</li><li><strong>True finality</strong> — TON ~1 s, optimistic path (reorg-exposed) · Satsuma ~6 s, <strong>provable</strong></li><li><strong>Throughput</strong> — TON horizontally unbounded via sharding · Satsuma one pipeline (hundreds to a few thousand tx/s)</li><li><strong>Scaling model</strong> — TON scale <em>out</em> (dynamic shards) · Satsuma scale <em>up</em> (a single chain)</li><li><strong>Execution</strong> — TON: TVM, async actors, FunC/Tact/Tolk · Satsuma: EVM, synchronous, Solidity</li><li><strong>Composability</strong> — TON async, non-atomic · Satsuma synchronous, <strong>atomic</strong></li><li><strong>Fees</strong> — TON rent + gas, heading feeless · Satsuma metered by resource use, no rent</li><li><strong>Trust model</strong> — TON public, permissionless, ~400 validators · Satsuma permissioned, single operator, end-to-end</li><li><strong>Speed paid for by</strong> — TON raised inflation ~0.6% → ~3.6% · Satsuma no dilution</li></ul><h3>What “sub-second” actually means</h3><p>TON’s headline number deserves an honest read, because it’s the crux of everything below. “Instant subsecond” is <strong>not</strong> instant finality. TON’s own docs describe three distinct timing layers:</p><ul><li><strong>Streaming push (30–100 ms):</strong> an optimistic notification that a transaction <em>looks</em> included — delivered before consensus commits it.</li><li><strong>Block production (~400 ms):</strong> the transaction lands in a shard block.</li><li><strong>True finality (~1 s):</strong> the block is committed and irreversible.</li></ul><p>The number people quote — the sub-100 ms “instant” feel — is the streaming layer surfacing state before it’s final. It’s a push-based optimistic-confirmation stream sitting <em>above</em> consensus. Think of it as a cache of “probably true” that consensus later ratifies.</p><p>And the trade-off is written into TON’s own guidance: acting on an optimistic confirmation carries reorg risk, and — this is the sharp edge — if a confirmed balance is later rolled back, <em>no invalidation notification is sent</em>. A value you displayed as confirmed can silently revert. TON’s advice for anything balance-critical is to wait for finality. So the real shape of it is ~400 ms of responsive feedback wrapped around ~1 s of actual settlement, with a reorg-exposure window in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KLSel1WRJzNH_cNnDoV2w.png" /></figure><p>There’s a deeper structural trade-off behind the whole speed-and-scale story. TON’s throughput comes from an asynchronous actor model and dynamic sharding — hot shards split to run in parallel, idle ones merge. That parallelism is real and powerful, but it gives up <strong>synchronous atomic composability</strong>: a TON contract can’t call another and read the result in the same transaction — it sends a message processed in a <em>later</em> block. And the extra block rate wasn’t free; sustaining it meant raising network inflation from ~0.6% to ~3.6%. Speed, partly funded by dilution.</p><h3>Where TON genuinely wins</h3><p>No spin — these are real, and worth saying plainly:</p><ul><li><strong>Raw latency.</strong> ~400 ms blocks and ~1 s finality versus our 2 s and ~6 s. Roughly 5–6× faster today.</li><li><strong>Scalability.</strong> Unbounded horizontal sharding versus our single pipeline. At the network level, orders of magnitude more aggregate capacity.</li><li><strong>Reach.</strong> A live, permissionless, consumer-scale network with hundreds of validators and Telegram-sized distribution.</li></ul><p>If your job is to be a global public consumer network, TON is extremely well built for it. That’s genuinely not the job Satsuma is doing.</p><h3>Could Satsuma close the gap? Yes — the useful 90%, cheaply</h3><p>Here’s the part that surprised me most when I did the measurement work: <strong>TON’s “instant” is two independent moves, and Satsuma can make both without adopting any of the async/sharding machinery that costs so much.</strong></p><p><strong>Lower the block time.</strong> Satsuma’s 2 seconds is a configuration parameter, not a protocol floor. Bringing it to ~500 ms pulls finality from ~6 s down to roughly ~1.5–3 s — squarely in TON’s ballpark. The one real constraint is one I measured directly: a block has to be produced, propagated, and imported within its slot, and I’ve watched block time degrade when a block gets too heavy for its window. So a shorter slot has to be paired with a proportionally smaller per-block budget and validated on the slowest validator. For a small permissioned validator set on good hardware, ~500 ms is comfortably feasible.</p><p><strong>Add an optimistic confirmation stream.</strong> This is the direct analogue of TON’s streaming layer, and the bigger perceived-latency win. Today our Ethereum JSON-RPC layer hands back a transaction hash and the client polls for the receipt. Instead, we could push status the instant a block author <em>includes</em> the transaction — a sub-100 ms “confirmed” signal — while final settlement lands underneath. Same optimistic trade-off TON makes, but with two advantages we keep: our finality is <strong>provable</strong> (a “finalized” transaction is a checkable guarantee, not a probability), and with a tiny validator set and short blocks, the reorg window is small and short-lived.</p><p>There’s a third lever worth naming, on throughput rather than latency: our EVM runs an interpreter with no compiled-code cache today, and the measurements show the write path is bound by that, not by hardware. A compiled-code cache or JIT is the lever that lifts EVM throughput — the same <em>kind</em> of move as TON’s streaming cache, in a different place. Put together, these are the ingredients of a faster Satsuma variant: shorter blocks, an optimistic stream, a compiled-code cache. <strong>TON-class feel, with none of the async model, sharding, or inflation.</strong></p><h3>But here’s the thing — we don’t need it</h3><p>Every one of those levers exists. I know how to pull them. And for what Satsuma is actually for, we’re not going to — because they solve problems our use case doesn’t have.</p><p>Satsuma is built for a specific kind of workload: <strong>an autonomous system</strong> — a controlled set of high-value operations that govern state, move value, and record their own verifiable history on a chain that can’t be quietly rewritten, with no human approving each step. That’s a <strong>correctness-and-trust problem, not a throughput problem.</strong> Measured against that job:</p><ul><li><strong>We don’t need to scale out.</strong> The workload is one entity’s low-volume, high-value actions — not millions of consumer transactions. Per-pipeline, we’re already in the same league as a single TON shard; TON’s giant numbers are the <em>sum across many shards</em>, which is capacity for a demand we don’t have.</li><li><strong>We don’t need the optimistic cache.</strong> An autonomous system acts on state and then can’t take it back. “Feels done but might silently revert” is precisely the wrong primitive for that — it’s a liability, not a feature. What it wants is “is done,” provably. That’s what our finality already gives.</li><li><strong>We don’t need sub-second.</strong> There’s no human staring at a spinner. A few seconds to <em>provable</em> settlement is not a constraint on an automated decision loop.</li></ul><p>And the things we <em>do</em> need, TON gives up to get its scale:</p><ul><li><strong>Synchronous atomic composability.</strong> Check governance <strong>and</strong> move treasury <strong>and</strong> emit an attestation in one atomic transaction — all-or-nothing. On an async actor model that’s several messages across several blocks, non-atomic, with no synchronous read-back. When governance, treasury, and control logic have to interact <em>correctly</em>, atomicity isn’t a nicety — it’s the whole game.</li><li><strong>Provable finality.</strong> “Finalized” as a hard, checkable guarantee, not an optimistic confirmation with a silent-reorg gap.</li><li><strong>A durable record.</strong> Contracts that persist on a one-time deposit, not one paying per-second storage rent that can freeze or delete an underfunded contract — bad news for a tamper-evident audit trail.</li><li><strong>Determinism and control.</strong> For a controlled, high-assurance workload, a closed chain operated end-to-end is the right tool. TON’s public, adversarial, asynchronous design is a liability here, not a benefit.</li></ul><h3>The takeaway</h3><p>This comparison isn’t a scoreboard. It’s a lesson in right-sizing. <strong>TON is the better general-purpose public consumer network. Satsuma is the better special-purpose foundation for an autonomous system</strong> — and those sentences don’t contradict each other.</p><p>The useful discipline is knowing which numbers matter for <em>your</em> job and ignoring the ones that don’t. I measured the gap, mapped exactly how to close the parts worth closing, and we’re deliberately leaving the rest — because the scale and the cache buy speed and reach at the cost of atomicity, provable settlement, and simplicity, and those three are the entire point of what we’re building.</p><p>If we ever need the faster variant, the plan is already written. We just don’t need it to prove the thing we’re proving.</p><p>The full design behind Satsuma — architecture, access model, fees, and measured performance — is in the <a href="https://www.satsuma.one/litepaper">Satsuma litepaper</a>. You can watch the chain settle blocks live at <a href="https://explorer.satsuma.one/">explorer.satsuma.one</a>. And if you’re building autonomous on-chain systems, that’s the crowd we’re gathering — come say hi in the <a href="https://t.me/web4builders">Telegram</a>.</p><p><em>This post was originally published on the </em><a href="https://engineering.satsuma.one/research/ton-vs-satsuma/"><em>Satsuma engineering blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bfb80051e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Satsuma]]></title>
            <link>https://medium.com/@brunopgalvao/introduction-to-satsuma-220eae99b52e?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/220eae99b52e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 00:00:16 GMT</pubDate>
            <atom:updated>2026-07-10T18:11:36.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ktjh7s1yF2qoYcRV" /></figure><p>A live, sovereign Solidity Layer-1 — Ethereum-compatible, final in seconds, public to read and permissioned to write. A visual tour of what Satsuma is and the choices that shape it.</p><p>Satsuma is a <strong>live, sovereign Layer-1 blockchain that runs Solidity smart contracts</strong>. It’s in production right now — sealing blocks, Ethereum-compatible, and open for anyone to read. This is the first post on the Satsuma engineering blog, so let’s take a visual tour: what Satsuma is, and the handful of deliberate choices that give it its shape.</p><h3>Solidity, not a subset</h3><p>Satsuma runs <strong>standard Solidity</strong> — not a dialect, not a restricted subset. The same contracts, the same language, the same mental model you already use on Ethereum. If you can write and deploy an ERC-20, an ERC-721, or a full DeFi protocol on an EVM chain, you can deploy it on Satsuma with the tools you already know.</p><p>That compatibility is the point. A new Layer-1 that asks developers to relearn everything starts with a tax nobody wants to pay. Satsuma removes that tax: bring your contracts, your libraries, and your workflow as-is.</p><h3>Public to read, permissioned to write</h3><p>Satsuma is a <strong>closed, permissioned Layer-1</strong> — and that asymmetry is a feature, not a limitation. Anyone can read the chain; only an approved set can write to it.</p><ul><li><strong>Public to read.</strong> Every block, address, and balance is open. The<a href="https://explorer.satsuma.one/">live explorer</a> streams the head in real time — no account, no wallet.</li><li><strong>Permissioned to write.</strong> Who can submit transactions is controlled, which keeps the network predictable and abuse-resistant. That matters when a chain backs real applications rather than open speculation.</li></ul><p>The result is transparency without the noise: the openness of a public ledger with the operational guarantees of a private network.</p><h3>Fast, and final</h3><p>Two numbers define the day-to-day feel of a chain: how often it produces blocks, and how quickly those blocks become irreversible.</p><p>Blocks seal roughly every <strong>two seconds</strong>, and finality is <strong>deterministic</strong> — once a block is finalized, it’s settled, with no probabilistic waiting and no reorgs to design around. For an application developer, a transaction you see confirmed is genuinely done, in seconds.</p><h3>Solidity enabled, out of the box</h3><p>Satsuma speaks EVM, so the standard Ethereum toolchain applies with no changes — the same contracts, the same Foundry/Hardhat workflow, the same wallets. <strong>Reading</strong> the chain is open to anyone; point any EVM tool at the RPC and query it:</p><p><strong>Writing</strong> is where the permissioning lives. Deploying contracts and sending transactions is plain Solidity — nothing Satsuma-specific to learn — but reserved for approved participants rather than open to the public. The capability is fully standard EVM; the <em>access</em> to write is controlled. And whatever does get written, anyone can read and audit in the <a href="https://explorer.satsuma.one/">explorer</a>.</p><h3>See it live</h3><p>The best way to understand Satsuma is to watch it run. The explorer at <a href="https://explorer.satsuma.one/"><strong>explorer.satsuma.one</strong></a> shows the live head, block times, and finality as they happen — a permissioned chain sealing blocks on schedule, in the open.</p><h3>Where this blog goes next</h3><p>This is the introduction; the next posts go deeper. Expect architecture write-ups, performance work, and head-to-head comparisons with other chains — with the numbers to back them up. Follow along on <a href="https://x.com/brunopgalvao">X</a> or <a href="https://t.me/web4builders">Telegram</a>, or grab the <a href="https://engineering.satsuma.one/rss.xml">RSS feed</a>.</p><p><em>Originally published at </em><a href="https://engineering.satsuma.one/posts/introduction-to-satsuma/"><em>https://engineering.satsuma.one</em></a><em> on July 10, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220eae99b52e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying your first contract to Polkadot in 5minutes]]></title>
            <link>https://medium.com/@brunopgalvao/deploying-your-first-contract-to-polkadot-in-5minutes-5cf190601b99?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf190601b99</guid>
            <category><![CDATA[polkadot]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 05:54:49 GMT</pubDate>
            <atom:updated>2024-12-11T04:08:17.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying your first contract to Polkadot in 5 minutes</h3><p>This tutorial will guide you on deploying a Solidity smart contract to Polkadot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXc0ddpWzl_U0vbqWPFyMQ.jpeg" /></figure><p>Recommended listening track:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1910648045%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fmoldovansound%2Ffeeric&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-38zHyYHCFzXtO1hB-2p4xMw-t500x500.jpg&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e48509a4a36cdd643ce476196ec9c62/href">https://medium.com/media/9e48509a4a36cdd643ce476196ec9c62/href</a></iframe><h3>TL;DR;</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTwT2eX58Rc8%3Flist%3DPLogPKTNJxUXnSfFkvHfFhlPahlcDc3xdg&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTwT2eX58Rc8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTwT2eX58Rc8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b30c533059f95d6b0fd9273a2b5a2a13/href">https://medium.com/media/b30c533059f95d6b0fd9273a2b5a2a13/href</a></iframe><h3>Get Started</h3><p>You will need the <a href="https://metamask.io/download">MetaMask</a> wallet:</p><ul><li><a href="https://metamask.io/download/">https://metamask.io/download</a></li></ul><p>We will be deploying to Asset Hub on the Polkadot test network: “Westend”.</p><p>Asset Hub is a system parachain on Polkadot.</p><blockquote>A parachain is an L1 blockchain that has its blocks finalized by the Polkadot Relay chain.</blockquote><p>Add Asset Hub parachain to the MetaMask wallet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ueoqpmQPpY5Cy7x4Zbn3Q.png" /><figcaption>MetaMask (Settings)</figcaption></figure><blockquote>Network name: Asset-Hub Westend Testnet</blockquote><blockquote>RPC URL URL: <a href="https://westend-asset-hub-eth-rpc.polkadot.io/">https://westend-asset-hub-eth-rpc.polkadot.io</a></blockquote><blockquote>Chain ID: 420420421</blockquote><blockquote>Currency Symbol: WND</blockquote><blockquote>Block Explorer URL: <a href="https://assethub-westend.subscan.io/">https://assethub-westend.subscan.io</a></blockquote><h3>Get some tokens</h3><p>Next go to the <a href="https://faucet.polkadot.io/westend?parachain=1000">Westend faucet</a> and request some tokens using your Ethereum account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2OpgvD2MscMsV8Nau-47Q.png" /></figure><p>On success you will have some WND tokens in your account.</p><p>We are now ready to deploy contracts to Asset Hub!</p><h3>Solidity Smart Contract</h3><p>Go to the <a href="https://remix.polkadot.io/">REMIX IDE</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_JtIbB9vCveGyJ7Ew1uLg.png" /><figcaption>REMIX IDE</figcaption></figure><p>Compile the _Storage.sol contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVaVMoZw2ztbCobsHbUdlQ.png" /><figcaption>Compile</figcaption></figure><p>Deploy the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRXTZasAr9PxO7ynuVzOFA.png" /><figcaption>Deploy</figcaption></figure><p>Once deployed, make sure to pin the contract so we can interact with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyvxf_9_GKcXMGQyWTbaJg.jpeg" /><figcaption>Pin</figcaption></figure><p>We can now interact with the contract’s methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RV2sT2Pq4VyuMUpLxsygew.png" /><figcaption>Store</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQyfKF1H2rProUCRabdbiQ.png" /><figcaption>Retrieve</figcaption></figure><p>Congratulations!</p><p>You successfully deployed a <strong>Solidity smart contract</strong> to Polkadot!</p><h3>Resources:</h3><ul><li>Learn: <a href="https://contracts.polkadot.io/">contracts.polkadot.io</a></li><li>Watch: <a href="https://youtu.be/GPuTt10dxKI?si=ImDzyxFvikSji6C3">Solidity on Polkadot</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf190601b99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your first ink! smart contract on Pop Network]]></title>
            <link>https://medium.com/@brunopgalvao/creating-your-first-ink-smart-contract-on-pop-network-6a3dff91e200?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a3dff91e200</guid>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 09:39:04 GMT</pubDate>
            <atom:updated>2024-04-14T09:39:04.111Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial developers will learn how to deploy an ink! smart contract to Pop Network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-rG3kZ7vSO3TL3ERgKlIA.png" /></figure><h3>Audience</h3><p>Developers who want to learn how to:<br>- use the <a href="https://github.com/r0gue-io/pop-cli">Pop CLI</a> tool to speed up development<br>- deploy smart contracts to <a href="https://github.com/r0gue-io/pop-node">Pop Network</a></p><h3>Learning Objectives</h3><p>On completion of this tutorial, developers will be able to:<br>- create, build, test, and deploy ink! smart contracts using <a href="https://github.com/r0gue-io/pop-cli">Pop CLI</a><br>- deploy smart contracts to <a href="https://github.com/r0gue-io/pop-node">Pop Network</a> locally and on <a href="https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.ibp.network%2Fpaseo">Paseo</a><br>- interact with the deployed contract</p><h3>Prerequisites</h3><p>Developers should have knowledge of the following:<br>- a firm understanding of the <a href="https://doc.rust-lang.org/book">Rust programming language</a><br>- a general concept of what smart contracts are<br>- general knowledge of Web3 and <a href="https://docs.substrate.io/learn/blockchain-basics">blockchain</a><br>- <a href="https://docs.substrate.io/tutorials/smart-contracts/prepare-your-first-contract">install</a> the Rust toolchain</p><h3>Installing Pop CLI</h3><p>Let’s install the powerful <a href="https://github.com/r0gue-io/pop-cli">Pop CLI</a> tool which will be used throughout this tutorial.</p><pre>cargo install — locked — git https://github.com/r0gue-io/pop-cli</pre><p>Make sure the <a href="https://github.com/r0gue-io/pop-cli">Pop CLI</a> tool has been installed correctly by running the pop command in your terminal.</p><pre>pop — help<br><br>An all-in-one tool for Polkadot development.<br>Usage: pop &lt;COMMAND&gt;<br>Commands:<br> new Generate a new parachain, pallet or smart contract<br> build Build a parachain or smart contract<br> call Call a smart contract<br> up Deploy a parachain or smart contract<br> test Test a smart contract<br> help Print this message or the help of the given subcommand(s)<br>Options:<br> -h, - help Print help<br> -V, - version Print version</pre><h3>Getting Started</h3><p>Questions:<br>1. What are ink! smart contracts?<br>2. What are the benefits of using the ink! programming language?<br>3. Why use ink! to develop smart contracts?<br>4. What makes ink! so nice?<br> <br>Take 10 minutes to skim over the [ink! documentation](<a href="https://use.ink/">https://use.ink</a>) and answer the above questions.</p><p><strong>ink! contracts are smart(er)</strong><br>ink! allows you to write smart contracts using Rust.<br>That means you get all the benefits of the Rust programming language:<br>- <a href="https://use.ink/why-rust-for-smart-contracts">https://use.ink/why-rust-for-smart-contracts</a></p><p>The ink! embedded domain-specific language (eDSL) retro-fits your Rust code with powerful features that enhance smart contract development. In doing so, ink! improves the developer ergonomics when it comes to using Rust for writing smart contracts.</p><p>Let’s create a simple ink! smart contract:</p><pre>pop new contract flipper<br><br>┌ Pop CLI : Generating new contract &quot;flipper&quot;!<br>│<br>◇ Smart contract created! Located in the following directory &quot;/flipper&quot;<br>│<br>└ cd into &quot;flipper&quot; and enjoy hacking! 🚀</pre><p>By default, when we generate an ink! smart contract using the command above, we get a template (the “flipper” template). It serves as a good starting point for contract development.</p><p>Let’s look at our first bit of ink! code.</p><pre>cd flipper</pre><p>You will see the following in this directory:</p><pre>flipper<br> └─ lib.rs<br> └─ Cargo.toml<br> └─ .gitignore</pre><p>Inside `lib.rs` you will find all the contract logic.</p><p>Take a moment to get familiar with the ink! programming language:<br>- <a href="https://use.ink/basics/contract-template">https://use.ink/basics/contract-template</a></p><h3>Building the ink! smart contract</h3><p>Let’s build flipper! Make sure you are inside the flipper directory and run the following command:</p><pre>pop build contract<br><br>┌ Pop CLI : Building a contract<br>│<br> [==] Checking clippy linting rules<br> Compiling proc-macro2 v1.0.79<br> Compiling unicode-ident v1.0.12<br> Compiling syn v1.0.109<br> Compiling equivalent v1.0.1<br> Compiling hashbrown v0.14.3<br> Compiling winnow v0.5.40<br> ….<br> Finished release [optimized] target(s) in 21.17s<br> Running `target/ink/release/metadata-gen`<br> [==] Generating bundle<br>◆ <br>│ Original wasm size: 21.3K, Optimized: 1.6K<br>│ <br>│ The contract was built in RELEASE mode.<br>│ <br>│ Your contract artifacts are ready. You can find them in:<br>│ /Users/bruno/src/flipper/target/ink<br>│ <br>│ - flipper.contract (code + metadata)<br>│ - flipper.wasm (the contract&#39;s code)<br>│ - flipper.json (the contract&#39;s metadata)<br>│ <br>└ Build completed successfully!</pre><p>Awesome, your contract is built!</p><p>With Pop CLI, you can also run your smart contract tests.</p><h3>Run your ink! smart contract unit tests</h3><pre>pop test contract<br><br>┌ Pop CLI : Building a contract<br>│<br> [==] Checking clippy linting rules<br> Compiling proc-macro2 v1.0.79<br> ….<br> Compiling flipper v0.1.0 (/Users/bruno/src/pop-cli/flipper)<br> Finished test [unoptimized + debuginfo] target(s) in 8.06s<br> Running unittests lib.rs (target/debug/deps/flipper-ff1505839f6873de)<br>running 2 tests<br>test flipper::tests::it_works … ok<br>test flipper::tests::default_works … ok<br>test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s<br>Doc-tests flipper<br>running 0 tests<br>test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s<br>└ Unit testing complete</pre><p>Okay, so you contract builds, your contract passes the tests. We can now deploy the contract.</p><h3>Deploy your contract locally</h3><p>In order to deploy an ink! smart contract locally we need to spin up a local instance of [Pop Network](<a href="https://github.com/r0gue-io/pop-node">https://github.com/r0gue-io/pop-node</a>).</p><p>Pop Network is a parachain meaning that it runs on the Polkadot Relay chain.</p><blockquote>To take a deep dive into how Parachains and the Relay chain work, go <a href="https://docs.substrate.io/tutorials/build-a-parachain">here</a>.</blockquote><p>We will use Pop CLI to spin up a live network locally on our machine.</p><p>In a separate directory, let’s create the configuration file for our local test network.</p><p>./network.toml</p><pre>[relaychain]<br>chain = &quot;rococo-local&quot;<br><br>[[relaychain.nodes]]<br>name = &quot;alice&quot;<br>validator = true<br><br>[[relaychain.nodes]]<br>name = &quot;bob&quot;<br>validator = true<br><br>[[parachains]]<br>id = 1000<br>chain = &quot;asset-hub-rococo-local&quot;<br><br>[[parachains.collators]]<br>name = &quot;asset-hub&quot;<br><br>[[parachains]]<br>id = 9090<br>default_command = &quot;pop-node&quot;<br><br>[[parachains.collators]]<br>name = &quot;pop&quot;</pre><p>We can now use the configuration file to spin up the network.</p><pre>pop up parachain -f ./network.toml -p https://github.com/r0gue-io/pop-node<br><br>┌ Pop CLI : Deploy a parachain<br>│<br>▲ The following missing binaries are required: polkadot-parachain-v1.9.0<br>│ <br>◆ Would you like to source them automatically now?<br>│ ● Yes / ○ No <br>│<br>⚙ They will be cached at /Users/bruno/Library/Caches/pop<br>│ <br>◐ Sourcing polkadot-parachain-v1.9.0…</pre><blockquote>The first time you run this command it will take some time. Grab some coffee.</blockquote><p>Once complete, you will get some output:</p><pre>....<br>◇ Sourcing complete.<br>│<br>◇ 🚀 Network launched successfully - ctrl-c to terminate<br>│ ⛓️ rococo-local<br>│ alice:<br>│ portal: https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56533#/explorer<br>│ logs: tail -f /var/folders/vl/txnq6gdj22s9rn296z0md27w0000gn/T/zombie-48a3549c-5ab9–43de-93f5–9057211f3846/alice/alice.log<br>│ bob:<br>│ portal: https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56537#/explorer<br>│ logs: tail -f /var/folders/vl/txnq6gdj22s9rn296z0md27w0000gn/T/zombie-48a3549c-5ab9–43de-93f5–9057211f3846/bob/bob.log<br>│ ⛓️ local_testnet: 9090<br>│ pop:<br>│ portal: https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56545#/explorer<br>│ logs: tail -f /var/folders/vl/txnq6gdj22s9rn296z0md27w0000gn/T/zombie-48a3549c-5ab9–43de-93f5–9057211f3846/pop/pop.log<br>│ ⛓️ asset-hub-rococo-local: 1000<br>│ asset-hub:<br>│ portal: https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56541#/explorer<br>│ logs: tail -f /var/folders/vl/txnq6gdj22s9rn296z0md27w0000gn/T/zombie-48a3549c-5ab9–43de-93f5–9057211f3846/asset-hub/asset-hub.log</pre><p>You now have the following running locally on your machine:</p><p><strong><em>rococo-local</em></strong><br>— this is the “Polkadot” Relay chain<br>— two validator nodes (alice &amp; bob) to run the rococo-local Relay chain<br> <br><strong><em>local_testnet</em></strong><br>— this is the Pop Network parachain<br>— one collator node is running for the Pop Network parachain<br> <br><strong><em>asset-hub-rococo-local</em></strong><br>— this is the Asset Hub system parachain that manages assets in Polkadot<br>— one collator node is running for this system chain<br> — it is useful to have a second parachain like this one to test cross-chain capabilities</p><p>Confirm that the Pop Network parachain is producing blocks by opening the PolkadotJS link in your browser:<br>- <a href="https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56545#/explorer">https://polkadot.js.org/apps/?rpc=ws://127.0.0.1:56545#/explorer</a><br>Replace the port number with the port number for the Pop Network parachain that is outputted in your terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zL5fnBmGs60NtHx5boqfZQ.png" /></figure><p>Cool. Now that we have Pop Network running we can now deploy our contract.</p><p>Keep the PolkadotJs App window open, specifically to see the recent events. After we deploy the contract, we will see the events displayed there.</p><p>You will need to know the RPC URL for Pop Network which was outputted in the terminal when you ran the `pop up` command.</p><pre>pop up contract -p ./flipper - constructor new - args &quot;false&quot; - suri //Alice - url ws://127.0.0.1:56545<br><br>┌ Pop CLI : Deploy a smart contract<br>│<br>◐ Doing a dry run to estimate the gas… ● Gas limit Weight { ref_time: 264725731, proof_size: 16689 }<br>│ <br>◇ Contract deployed and instantiated: The Contract Address is &quot;5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A&quot;<br>│<br>└ Deployment complete</pre><p>The contract has been deployed!</p><blockquote>Save the contract address as we will be used in the next step to interact with the contract.</blockquote><p>You can also confirm that the contract was deployed in the recent events in Polkadot JS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLI5SqTRJmy-T3R7ucizKA.png" /></figure><h3>Interacting with our contract</h3><p>Now that the contract is live, we can start interacting with it.</p><p>Grab the contract address that was outputted from the previous step.</p><blockquote>If you lost the address, you can always pull up PolkadotJs Apps and check the chain state for the contract address.</blockquote><pre>pop call contract -p ./flipper - contract 5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A - message get - suri //Alice - url ws://127.0.0.1:56545<br><br>┌ Pop CLI : Calling a contract<br>│<br>◐ Calling the contract… ⚙ Result: Ok(false)<br>│ <br>▲ Your call has not been executed.<br>│ <br>▲ To submit the transaction and execute the call on chain, add -x/ - execute flag to the command.<br>│ <br>└ Call completed successfully!</pre><p>The result here is <em>false</em> meaning that <em>value</em> in the flipper storage is set to <em>false</em>.</p><p>Let’s try <em>flipping</em> it.</p><pre>pop call contract -p ./flipper - contract 5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A - message flip - suri //Alice - url ws://127.0.0.1:56545 -x<br><br>┌ Pop CLI : Calling a contract<br>│<br>◐ Doing a dry run to estimate the gas… ⚙ Gas limit Weight { ref_time: 382198493, proof_size: 18636 }<br>│ <br>◓ Calling the contract… ⚙ Events<br>│ Event Balances ➜ Withdraw<br>│ who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY<br>│ amount: 1.550397502mUNIT<br>│ Event Contracts ➜ Called<br>│ caller: Signed(5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY)<br>│ contract: 5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A<br>│ Event TransactionPayment ➜ TransactionFeePaid<br>│ who: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY<br>│ actual_fee: 1.550397502mUNIT<br>│ tip: 0UNIT<br>│ Event System ➜ ExtrinsicSuccess<br>│ dispatch_info: DispatchInfo { weight: Weight { ref_time: 1302708493, proof_size: 9064 }, class: Normal, pays_fee: Yes }<br>│ <br>└ Call completed successfully!</pre><blockquote>Notice the `-x` flag at the end of the `pop call` command. This is needed because we are executing a transaction on the network and it will cost gas.</blockquote><p>Did it work? Let’s see if the value has been flipped.</p><pre>pop call contract -p ./flipper - contract 5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A - message get - suri //Alice - url ws://127.0.0.1:56545<br><br>┌ Pop CLI : Calling a contract<br>│<br>◐ Calling the contract… ⚙ Result: Ok(true)<br>│ <br>▲ Your call has not been executed.<br>│ <br>▲ To submit the transaction and execute the call on chain, add -x/ - execute flag to the command.<br>│ <br>└ Call completed successfully!</pre><p>The <em>value</em> is now <em>true</em>.</p><p>Awesome we now know how to make calls to our smart contract.</p><h3>Running end-to-end tests of your contract</h3><p>Make sure you are in the flipper directory:</p><pre>cd flipper</pre><p>If you look at the flipper ink! smart contract, you will notice it has end-to-end tests at the <em>end</em> of the <em>lib.rs</em> file.</p><p>The ink! e2e tests runs against a <a href="https://github.com/paritytech/substrate-contracts-node">substrate-contracts-node</a>.</p><p>Download and save the <a href="https://github.com/paritytech/substrate-contracts-node">substrate-contracts-node</a>.</p><p>Run the e2e tests:</p><pre>export CONTRACTS_NODE=&quot;/Users/bruno/src/substrate-contracts-node/target/debug/substrate-contracts-node&quot;<br>pop test contract - features e2e-tests<br><br>┌ Pop CLI : Starting end-to-end tests<br>│<br> Finished test [unoptimized + debuginfo] target(s) in 0.83s<br> Running unittests lib.rs (target/debug/deps/flipper-508d8cf8af185e86)<br>running 5 tests<br>test flipper::e2e_tests::e2e_test_deployed_contract … ignored<br>test flipper::tests::it_works … ok<br>test flipper::tests::default_works … ok<br> Compiling toml_datetime v0.6.5<br> Compiling toml_edit v0.20.2<br> ….<br> Finished release [optimized] target(s) in 9.03s<br> Running `target/ink/release/metadata-gen`<br>test flipper::e2e_tests::default_works … ok<br>test flipper::e2e_tests::it_works … ok<br>test result: ok. 4 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 47.56s<br>Doc-tests flipper<br>running 0 tests<br>test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s<br>└ End-to-end testing complete</pre><p>Passed!</p><h3>Deploy on the Pop Network TestNet</h3><p>Once you have battle-tested your smart contract using the armor of unit and e2e tests, you are ready to test your smart contract on a live network: the Pop Network TestNet.</p><p>Let’s deploy.</p><p>The test network for Polkadot is <a href="https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpaseo.rpc.amforc.com">Paseo</a>.</p><p>You can find Pop Network running on Paseo <a href="https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc2.paseo.popnetwork.xyz">here</a>.</p><p>Use the <a href="https://faucet.polkadot.io/paseo">Paseo faucet</a> to fund Alice’s Paseo account with some PAS tokens. PAS tokens are the equivalent of DOT on Polkadot.</p><p>Alice’s account is: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY</p><p>Go to the <a href="https://faucet.polkadot.io/paseo">Paseo faucet</a> and request some PAS tokens for Alice.</p><p>Since Pop Network uses the Relay chain’s native token as its native token, we will need to get the PAS tokens that is in your account on Paseo into Pop Network so we can deploy the contract.</p><p>We will need to add Alice to our <a href="https://polkadot.js.org/extension">PolkadotJs Wallet extension</a>. We can do that by using Alice’s secret seed: 0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKDYBxpiAnFlPHJSq1Ut-g.png" /></figure><blockquote>Remember this is for development purposes. <br>In production you would already have an existing wallet to use.</blockquote><p>Now that we have Alice’s account in our PolkadotJs Wallet Extension, we can use the following for teleporting PAS tokens to Pop Network:<br>- <a href="https://onboard.popnetwork.xyz/">https://onboard.popnetwork.xyz</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0Wz2T_hpz3Y_rLMFcp9gQ.png" /></figure><p>Cool! Now that you have some PAS tokens on Pop Network, we can deploy.</p><pre>pop up contract - constructor new - args &quot;false&quot; - suri 0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a - url wss://rpc1.paseo.popnetwork.xyz<br><br>┌ Pop CLI : Deploy a smart contract<br>│<br>◐ Doing a dry run to estimate the gas… ● Gas limit Weight { ref_time: 266641786, proof_size: 16689 }<br>│ <br>◇ Contract deployed and instantiated: The Contract Address is &quot;5GE1BaqUsbh4ty1c6Ko1kkAp2AEZQCDhpvtKpJJ1Q3ex1xzC&quot;<br>│<br>└ Deployment complete</pre><p>You can now take the contract address and check the chain state to confirm that the contract exists</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGG_qyhRdQA8kcSy4BaVWQ.png" /></figure><p>Let’s add the contract to our Contracts UI in PolkadotJS Apps. Click on “add an existing contract”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9nLExsg9Tjp0qd3leZkSA.png" /></figure><p>Add the contract address along with the `flipper.contract` file found inside `flipper/target/ink/flipper.contract`</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyDRudc7zRSf-hHwPhmDzQ.png" /></figure><p>Save. You can now see your newly uploaded contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YgxXcswiGSwLxrWIXnF0A.png" /></figure><p>Done!</p><h3>Resources</h3><p>- <a href="https://use.ink/">https://use.ink</a></p><h3>Feedback</h3><p>&gt; [Take a minute to give us feedback on this tutorial so we can improve it!](<a href="https://forms.gle/tABmLwtqYPUHArRQ9">https://forms.gle/tABmLwtqYPUHArRQ9</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a3dff91e200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Substrate]]></title>
            <link>https://medium.com/@brunopgalvao/substrate-cfeb13333f2c?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfeb13333f2c</guid>
            <category><![CDATA[polkadot]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[substrate]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 07:46:25 GMT</pubDate>
            <atom:updated>2024-03-24T10:52:38.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro to Substrate</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F14018275%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ftribalneed%2Fthe-life-of-the-electronomad%3Fsi%3Da56e2af2996b4f4c992cd3279d79fb84%26utm_source%3Dclipboard%26utm_medium%3Dtext%26utm_campaign%3Dsocial_sharing&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-000035085939-jh56y5-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd359e3316407631be65e7965f27cdf3/href">https://medium.com/media/cd359e3316407631be65e7965f27cdf3/href</a></iframe><blockquote>Recommended listening track</blockquote><h3>Substrate</h3><p>A Rust-based blockchain framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV6ZYub5K4bQVHCNo1yIbg.png" /></figure><blockquote>Substrate: a playground for blockchain components.</blockquote><h3>Preface</h3><p>The plasticity of Substrate.</p><p>The <strong>diagrams</strong> in this article were inspired by Dutch artist <a href="https://en.wikipedia.org/wiki/Piet_Mondrian">Piet Mondrian</a><a href="https://en.wikipedia.org/wiki/Piet_Mondrian)&#39;s">’s</a> artwork. Mondrian is well-known for founding the <a href="https://en.wikipedia.org/wiki/Neoplasticism">Neoplasticism</a> art movement. Neoplasticism is characterized by abstract geometric forms and primary colors. It involves a reduction of visual elements to their essential qualities of form and color, stripped of representational or symbolic associations, to achieve a pure, universal expression of visual harmony.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7PWDJXR_jscXMXFMuIx23A.png" /></figure><blockquote><a href="https://en.wikipedia.org/wiki/Composition_with_Red,_Blue_and_Yellow">Composition with Red, Blue and Yellow</a></blockquote><p><strong>Let’s get started.</strong></p><h3>Substrate</h3><blockquote>Location of where the <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate">Substrate code</a> resides inside the <a href="https://github.com/paritytech/polkadot-sdk">Polkadot SDK repo</a>:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIgZVtOD3tZFlXi93n530g.png" /></figure><h3>TLDR;</h3><ul><li>Substrate is a Rust framework for building blockchains</li><li>100+ Substrate-based blockchains are running in production</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_cbJh1WQMy8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_cbJh1WQMy8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_cbJh1WQMy8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b4731d4db0d1b41306cae42e573819/href">https://medium.com/media/95b4731d4db0d1b41306cae42e573819/href</a></iframe><blockquote>This video is the short-form of this article.</blockquote><h3>What is Substrate?</h3><p>After two years of working at <a href="https://www.parity.io/">Parity Technologies</a> as a Substrate Developer, my definition of Substrate is:</p><blockquote>Substrate is an open-source, battle-tested, Rust framework for building future-proof blockchains optimized for most use cases — built by developers for developers.</blockquote><h3>Why is there a need for a blockchain framework?</h3><p>To answer this question, let’s explore the history of the original creators of Substrate:</p><p><a href="https://github.com/paritytech">Parity Technologies</a> — the engineering company behind <a href="https://polkadot.network/">Polkadot</a>.</p><p>When Parity Technologies started building the <a href="https://polkadot.network/">Polkadot</a> blockchain network the typical method for building a blockchain back then was to either fork an existing blockchain such as Ethereum or write your own blockchain from scratch. The Parity engineering founders wanted to build an innovative chain without the constraints of Ethereum and so they began to build Polkadot from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUVojiADbGUyI7ocPoGE1w.png" /></figure><p>Building Polkadot was not their first rodeo show. In their early days, Parity created a popular Ethereum client as well as a Bitcoin client — these are production-level blockchain nodes. So that being said, Parity had a wealth of engineering knowledge around creating blockchains.</p><p>With little time, they saw that several components involved in building the Polkadot blockchain network could be re-used to build other blockchains. Components such as networking, storage, transaction queue, and consensus. These components are common in most blockchains and should not have to be built from scratch. Parity placed a bet that the future would be multi-chain. Polkadot is this bet, a layer 0 chain where other chains can be <em>deployed</em> upon, inherit the Polkadot billion dollar security, and interop seamlessly with other chains deployed on the Polkadot network. The future was blockchains, many blockchains. Specialized blockchains that could interop with each other in a secure manner. The need for a blockchain framework was ripe.</p><h3>Brief History of Polkadot</h3><p>The idea of <a href="https://polkadot.network/">Polkadot</a> at the time came from the CTO of Ethereum — Dr. Gavin Wood. Prior to branching off and creating Polkadot, Gav was the CTO and a Co-Founder of Ethereum. He helped design and build Ethereum and created the Solidity programming language. According to him, Ethereum was built as a prototype — and hence why we see some of the inherent issues in the protocol nowadays e.g. scalability issues, exuberant gas fees, slow upgrades. Gav had a vision; he wanted to take the protocol to next level. But due to the constraints of Ethereum, the next iteration would have to be built out separately, hence he spun out, founded Parity Technologies, and began work on Polkadot.</p><p>In one way, Bitcoin served as a proof-of-concept for Ethereum. And in a similar light, one could say Ethereum served as a proof-of-concept for Polkadot.</p><p>Let’s come back to Substrate, the generic blockchain framework…</p><blockquote>Substrate takes all of our lessons learned in building Ethereum and Polkadot and distills that down into a stack of tooling that allows you to get all of those same rewards… for free.<br> — Dr. Gavin Wood</blockquote><p>As the Parity engineers started building out Polkadot, they put all the components involved in building and running a blockchain into what was the beginning of a framework — Substrate.</p><blockquote>Substrate is, “a set of libraries for doing all the things that are really annoying about writing blockchains.” <br> — Robert Habermeier</blockquote><h3>Building a blockchain is hard</h3><p>Building a blockchain from scratch is <strong>hard</strong> and takes a lot of resources.</p><p>It is <strong>costly</strong>, takes <strong>time</strong>, and requires <strong>specialized knowledge</strong>:</p><p>- Cryptographers<br>- Security researchers<br>- Networking engineers<br>- Devops personnel (to coordinate updates)<br>- Veteran Engineers</p><p>Here is a list of common components involved in building a blockchain:</p><p>- Storage / Database<br>- Networking<br> — Peer discovery, block and transaction gossiping, RPC Server<br>- Transaction Queue<br>- Consensus<br> — Proof of Stake, Proof of Authority, Proof of Work, etc.<br>- Cryptographic primitives<br>- Block format<br>- Light client support</p><p>Substrate abstracts all of this for the developer yet makes them available for customization if desired via Rust generics, types, and traits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzKRvgmwWKB-GPRuS2upWA.png" /></figure><p>By abstracting out core common functionalities in blockchains, developers can focus on the number one most common innovative feature of a blockchain — the <strong>state transition function</strong> (STF) — how your blockchain executes blocks — in Substrate this is called the <strong>runtime</strong> of the Substrate blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brzu8KrNXlKj2rwCY3QNvg.png" /></figure><p>The Substrate runtime is the business or application logic of the chain. It is where developers define what transactions on their chain do, in essence, what their blockchain does.</p><p>If developers are not required to invest obscene amounts of time in figuring out how innate details of P2P transaction gossiping works or how to write cryptographic primitives from scratch and instead can take that time to focus on their blockchain’s business logic then all of a sudden devs can bring innovative blockchain solutions to the world. That is what Substrate does. Substrate opens up whole new worlds of design space and potential for blockchain innovation.</p><p>To note, yes, if your team’s business solution is to come up with a novel consensus algorithm (consensus in Substrate lies <em>mostly</em> in the node-side) then you can leverage the generic nature of Substrate’s code to hand-roll your own consensus algorithm. <a href="https://alephzero.org/">AlephZero</a> did this. They have custom finality, are DAG-based, and have 1s block time… all using the Substrate framework.</p><p>However, most blockchain business cases are built as STF logic.</p><p>Substrate allows for writing STF business logic faster (with less lines of code) with FRAME.</p><h3>FRAME</h3><p>Informal definition:</p><blockquote>The <strong>frame</strong>work within the Substrate framework.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dp9glw9B7MiLGdRmi0O_Pw.png" /></figure><p>Formal definition:</p><blockquote>Framework for Runtime Aggregation of Modularized Entities (FRAME)</blockquote><p>In essence, it is the framework within Substrate for building runtimes.</p><blockquote>Substrate was born from the vision that developers shouldn’t have to recreate fundamentals when building and optimizing a blockchain.</blockquote><p>That includes common aspects of business logic.</p><p>FRAME consists of the following:</p><p>- modules with business logic (which we call <strong>pallets</strong>)<br>- support libraries to aid development</p><p>With FRAME, one can build runtimes <strong><em>faster</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ziOTeye5LTwqw7cXPUSuVg.png" /></figure><p>These pallets can be found in <a href="https://github.com/paritytech/polkadot-sdk">Polkadot SDK</a> &gt; <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate">Substrate</a> &gt; <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame">FRAME</a></p><p>Pallets are the building blocks of your runtime.</p><p>The Polkadot SDK repo already comes with many pre-built, audited pallets for one to drop into the codebase and hit the ground running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s58OpDAAoPIH8SBlyB-Z2g.png" /></figure><p>Intermission track:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F738715381%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ftribalneed%2Fmoonlight-invasion%3Fsi%3D38ecf78bf27d42a69908c9f574278d8e%26utm_source%3Dclipboard%26utm_medium%3Dtext%26utm_campaign%3Dsocial_sharing&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-000662836021-vq43cr-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04a82630217f9abbdc174b0a765ce59/href">https://medium.com/media/e04a82630217f9abbdc174b0a765ce59/href</a></iframe><h3>Forkless Upgrades</h3><p>Substrate runtimes get compiled down to WebAssembly (Wasm) and stored in the chain’s database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lV6ZYub5K4bQVHCNo1yIbg.png" /></figure><p>Therefore upgrading your chain is really easy — just swap the on-chain Wasm blob!</p><p>When developers build with Substrate, they are inherently building a future-proof chain because of this feature.</p><p>Substrate was designed from the ground-up with the concept of forkless upgrades.</p><p>That Wasm is uploaded, stored on-chain, and it is the logic of the running chain. The database stores the state of the chain which includes the Wasm blob.</p><p>To update the logic of the chain, one simply uploads a new Wasm blob and all the nodes automagically sync with the new chain logic seamlessly.</p><p>So as a recap let’s go over the flow of upgrading a chain the legacy way vs the Substrate way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NivqqiqNML5saNjvAsxyRg.gif" /></figure><blockquote>Often forks arise in legacy upgrades</blockquote><p><strong>Updating the network -&gt; the <em>old</em> way</strong></p><p>Typically, in a non-Substrate world, if one wants to upgrade their blockchain, they would have to:</p><p>1. Modify the blockchain code to introduce a new feature (or fix)<br>2. Running nodes would have to replace their binary in order to run the new code<br>3. Nodes who do not update would be left behind<br> — Often there is a lengthy planned coordination for nodes to upgrade<br>4. Depending on the code change, there could be a permanent fork in the network, creating two networks</p><p>Things to note on the above:</p><p>- The decision-making in updating the network often happens off-chain<br>- Because of human coordination, it takes a long time to upgrade the network<br>- Network protocol was not built from the ground-up to accommodate updates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rdu1_Fpq3biFjb0yxX2RzA.gif" /></figure><p><strong>Updating the network -&gt; the Substrate way</strong></p><p>1. A new feature (or fix) is added to the code<br>2. A new runtime with the fresh code is compiled to Wasm<br>3. An on-chain governance protocol takes place to vote on whether the runtime should be upgraded or not<br>4. If the on-chain governance votes aye, the upgrade happens seamlessly<br> — All nodes that are connected to the network are automatically upgraded</p><p>Things to note with the above</p><p>- Trust-less-ly upgradeable<br>- Fast, iterable, on-chain<br>- Substrate voting mechanism</p><p>Often, in the ethos of Web3, one does not want create a centralized decision-making process where the decision-making is off-chain or limited to a centralized entity. Substrate has a number of pre-built pallets that offer various means for one to create a robust governance system for decision-making on their chain.</p><h3>Governance</h3><p>Substrate offers a number of well-thought out pieces of governance logic that is available to be used and configured.</p><p>It is an opt-in feature.</p><p>One could have something as simple as using <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/collective">pallet collective</a> with <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/membership">pallet membership</a> and have a body do the decision-making for their chain.</p><p>OR</p><p>One could take that a step further and couple it with <a href="https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/democracy">pallet democracy</a> to have a more sophisticated voting / proposal / referenda system for their chain.</p><p>With a nice governance setup, things like voting on the next chain’s upgrade is built into the chain’s protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0neW2xB_cZPkPBY-FATNtA.png" /></figure><blockquote>Source: <a href="https://wiki.polkadot.network/docs/learn-governance">https://wiki.polkadot.network/docs/learn-governance</a></blockquote><p>The above is an example of what Polkadot calls “Governance V1”. The above is constructed with Substrate FRAME governance pallets.</p><p>The beautiful thing about governance on Substrate is that it is iterable, one could improve the governance system over time. Polkadot has done this. It started with Governance V1 and has now iterated to a brand new governance system using Substrate called <a href="https://wiki.polkadot.network/docs/learn-polkadot-opengov">OpenGov</a>. Several Substrate-based chains have followed suit and upgraded their chain to accomodate for an OpenGov governance system on their chain as well.</p><p>Let’s spin back a bit, many Substrate features have been covered thus far.</p><p>The features themselves are a good enough reason to use Substrate if someone were looking to build a L1 blockchain. However, from a business perspective, why should one consider to use Substrate?</p><h3>Why Substrate?</h3><p>&gt; General Answer.</p><p>Founders and developers can be confident that their blockchain is <strong>ready</strong> for whatever the <strong>future</strong> brings.</p><p>Focus on crafting the business logic that makes their chain unique and innovative with the additional benefits of flexibility, upgradeability, open source licensing, and battle-tested code.</p><p>With Substrate, devs can have complete creative control over the application they want to build. Devs can select predefined application logic from a large library of open source pallets and templates to speed up their development time. Not finding what they need in the current library? That’s not a problem — it’s an opportunity to build a custom pallet.</p><h3>Why Substrate?</h3><p>&gt; My Answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DkcOPOmE2Esj_PP-rshtg.png" /></figure><blockquote>+100 Substrate-based parachains in production, this is not counting Substrate solo-chains</blockquote><p>The strong tech and Web3 ethos that is unparalleled in Polkadot *drips* down into the Substrate framework e.g. sophisticated on-chain governance, production Substrate chains that have already undergone countless runtime upgrades, and last but not least the community — the tightly, interwoven community.</p><p>There are technical discussions happening on GitHub issues, PRs, the <a href="https://substrate.stackexchange.com/">Substrate Stack Exchange</a>, with lengthier discussions happening on the Polkadot Forum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*oYcStDcDl5kldQtXDCpr6A.gif" /></figure><blockquote><a href="https://substrate.stackexchange.com/">https://substrate.stackexchange.com</a></blockquote><p>Here is a Substrate Stack Exchange discussion around the difference between the Assets pallet and the Balances pallet:</p><blockquote><a href="https://substrate.stackexchange.com/questions/711/when-should-i-use-balances-pallet-and-when-should-i-use-assets-pallet">https://substrate.stackexchange.com/questions/711/when-should-i-use-balances-pallet-and-when-should-i-use-assets-pallet</a></blockquote><p>Here is an example of a team that is discussing building a fast Substrate blockchain and what it would take:</p><blockquote><a href="https://forum.polkadot.network/t/decentralized-futures-proposal-slap-simple-layer-for-accelerated-payments">https://forum.polkadot.network/t/decentralized-futures-proposal-slap-simple-layer-for-accelerated-payments</a></blockquote><p>Collaboration does not stop in online discussions, developers also meet at several events around the world, throughout the year, such as <a href="https://polkadot.network/ecosystem/events/decoded-2023/">Polkadot Decoded</a>, <a href="https://polkadot.network/ecosystem/events/sub0/">sub0</a>, Polkadot Summit (a special, invite-only event where ecosystem builders give feedback on Polkadot and help shape its future), and the <a href="https://polkadot.network/development/blockchain-academy">Polkadot Blockchain Academy</a>.</p><h3>Where to start?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYWIe3kEAM7tTTY98aRfAg.png" /></figure><p>Notice the chart above. Customizing the Substrate Node e.g. custom consensus algorithm has the most complexity. Building a blockchain without FRAME is second in complexity. Both are possible with the generic nature of how Substrate has been written, but the learning curve is higher.</p><p>The sweet spot is in building a blockchain with FRAME.</p><p>However, building a blockchain may not fit all use cases.</p><p>In most use cases, writing a smart contract is sufficient.</p><p>If you notice, implementing your business use case with smart contracts has the lowest development complexity and can be done in a short period of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJj3Zm492iI5VeQq3r11jw.png" /></figure><p>Better yet, Substrate supports smart contracts — a special flavour of smart contracts: <a href="https://use.ink/">ink! smart contracts</a>. With ink!, one can write contract logic in <strong>Rust</strong>!</p><p>You invest in skilling your team up in Rust, test your business use case by writing ink! smart contracts, attain market-fit, then, if needed, expand to a Substrate blockchain. The nice thing being that your team will already be warmed up to Substrate and Rust by using ink!.</p><p>ink! is an embedded domain specific language (eDSL). Writing ink! smart contracts is like butter.</p><p>ink! smart contracts compiles down to Wasm so you get that extra boost in performance over Solidity.</p><p>ink! Wasm contracts run on a Substrate pallet called pallet contracts. So any Substrate-based chain that is running pallet contracts can run ink! smart contracts.</p><h3>Deploying your ink! Smart Contracts</h3><blockquote>Deploy on Polkadot</blockquote><p>Okay, so you write your magnificent use case with ink! smart contracts, but where do you deploy it?</p><p>You want to deploy it on Polkadot right?</p><p>But Polkadot is a Relay Chain.</p><p>So that is where <a href="https://pop.r0gue.io/">Pop Network</a>, a Polkadot blockchain, comes into the picture.</p><p>With <a href="https://pop.r0gue.io/">Pop Network</a>, developers can use DOT to deploy ink! smart contracts to the Polkadot Network.</p><p><a href="https://pop.r0gue.io/">Pop Network</a> is an ink! smart contract parachain, running on Polkadot.</p><p>Pop Network is in its early stages of development.</p><blockquote>For some alpha updates join the <a href="https://t.me/Pop_Network">Pop Network Telegram</a>.<br>We are also looking for collaboration:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_zNZ-eGaD15txLPsgwu8A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfeb13333f2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Express API with Sequelize CLI and Express Router]]></title>
            <link>https://levelup.gitconnected.com/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/963b6e274561</guid>
            <category><![CDATA[sequelize-cli]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 19:14:51 GMT</pubDate>
            <atom:updated>2020-07-03T20:01:09.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*fygqfizATFjt6ALek2W1jg.png" /></figure><p>Building a full-fledged Node.js API can be done fairly easily using Sequelize for object relational mapping and Express as the framework for a server — and Express’ Router class is a useful tool for handling your app’s routes in a modular, organized way.</p><p>In this walkthrough, we’ll build a Sequelize project including associations and seed data, then use Express Router to define the routes for our server. Finally, we’ll deploy our app to <a href="https://www.heroku.com/">Heroku</a> to create a publicly accessible API.</p><h3>Creating the Sequelize application</h3><p>We’ll move as quickly as possible through our Sequelize setup in order to get to using Router — but we’ll include notes along the way for those who want to know more about using the Sequelize CLI or defining Sequelize associations.</p><p>Let’s start by installing Postgres, Sequelize, and the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> in a new project folder we’ll call express-api-using-router:</p><pre>mkdir express-api-using-router<br>cd express-api-using-router<br>git init<br>npm init -y<br>npm install sequelize pg &amp;&amp; npm install --save-dev sequelize-cli</pre><p>Let’s also add a .gitignore file to ease deployment later:</p><pre>echo &quot;<br>/node_modules<br>.DS_Store<br>.env&quot; &gt;&gt; .gitignore</pre><p>Next we will initialize a Sequelize project, then open the directory in our code editor:</p><pre>npx sequelize-cli init<br>code .</pre><blockquote>To learn more about the Sequelize CLI commands below, see:<br><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6"><strong>Getting Started with Sequelize CLI</strong></a></blockquote><p>Let’s configure our Sequelize project to work with a Postgres database. Find config.json in the /config directory and change the code to look like this:</p><pre>{<br>  &quot;development&quot;: {<br>    &quot;database&quot;: &quot;projects_api_development&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;test&quot;: {<br>    &quot;database&quot;: &quot;projects_api_test&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;production&quot;: {<br>    &quot;use_env_variable&quot;: &quot;DATABASE_URL&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;,<br>    &quot;dialectOptions&quot;: {<br>      &quot;ssl&quot;: {<br>        &quot;rejectUnauthorized&quot;: false<br>      }<br>    }<br>  }<br>}</pre><blockquote>Note: For production we use use_env_variable and DATABASE_URL. We are going to deploy this app to <a href="https://www.heroku.com/">Heroku</a>. Heroku is smart enough to replace DATABASE_URL with the production database, which we’ll see in action late<em>r.</em></blockquote><p>Now we can tell Sequelize CLI to create the Postgres database:</p><pre>npx sequelize-cli db:create</pre><h3>Defining models and adding seed data</h3><p>Our demonstration app will associate users with certain projects. Let’s start by creating a User model using the Sequelize CLI:</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string</pre><p>Running model:generate automatically creates both a model file and a migration with the attributes we’ve specified. Now we can execute the migration to create the Users table in our database:</p><pre>npx sequelize-cli db:migrate</pre><p>Now let’s create a seed file:</p><pre>npx sequelize-cli seed:generate --name users</pre><p>You will see a new file in the/seeders directory. In that file, paste the code below, which will create entries in your database for three users:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Users&#39;, [{<br>      firstName: &#39;John&#39;,<br>      lastName: &#39;Doe&#39;,<br>      email: &#39;john@doe.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      firstName: &#39;John&#39;,<br>      lastName: &#39;Smith&#39;,<br>      email: &#39;john@smith.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      firstName: &#39;John&#39;,<br>      lastName: &#39;Stone&#39;,<br>      email: &#39;john@stone.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Users&#39;, null, {});<br>  }<br>};</pre><p>You’ll note that we’ve named all three users “John”… just because. Now let’s add a Project model so that we can give these Johns something to do:</p><pre>npx sequelize-cli model:generate --name Project --attributes title:string,imageUrl:string,description:text,userId:integer</pre><p>Now we’ll create associations between the two models.</p><blockquote>To learn more about creating Sequelize associations, see:<br><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233"><strong>Creating Sequelize Associations with Sequelize CLI</strong></a></blockquote><p>First, find user.js in the /models subdirectory and replace the code with this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const Project = sequelize.define(&#39;Project&#39;, {<br>    title: DataTypes.STRING,<br>    imageUrl: DataTypes.STRING,<br>    description: DataTypes.TEXT,<br>    userId: DataTypes.INTEGER<br>  }, {});<br>  Project.associate = function (models) {<br>    // associations can be defined here<br>    Project.belongsTo(models.User, {<br>      foreignKey: &#39;userId&#39;,<br>      onDelete: &#39;CASCADE&#39;<br>    })<br>  };<br>  return Project;<br>};</pre><p>Now find project.js in the same directory and replace the code with this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const User = sequelize.define(&#39;User&#39;, {<br>    firstName: DataTypes.STRING,<br>    lastName: DataTypes.STRING,<br>    email: DataTypes.STRING,<br>    password: DataTypes.STRING<br>  }, {});<br>  User.associate = function (models) {<br>    // associations can be defined here<br>    User.hasMany(models.Project, {<br>      foreignKey: &#39;userId&#39;<br>    })<br>  };<br>  return User;<br>};</pre><p>Finally, we’ll add the foreign key to the newest migration file. You should see two files in your /migrations subdirectory. Look for the filename that ends with create-project.js and change the code inside to the below:</p><pre>&#39;use strict&#39;;<br>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.createTable(&#39;Projects&#39;, {<br>      id: {<br>        allowNull: false,<br>        autoIncrement: true,<br>        primaryKey: true,<br>        type: Sequelize.INTEGER<br>      },<br>      title: {<br>        type: Sequelize.STRING<br>      },<br>      imageUrl: {<br>        type: Sequelize.STRING<br>      },<br>      description: {<br>        type: Sequelize.TEXT<br>      },<br>      userId: {<br>        type: Sequelize.INTEGER,<br>        onDelete: &#39;CASCADE&#39;,<br>        references: {<br>          model: &#39;Users&#39;,<br>          key: &#39;id&#39;,<br>          as: &#39;userId&#39;,<br>        }<br>      },<br>      createdAt: {<br>        allowNull: false,<br>        type: Sequelize.DATE<br>      },<br>      updatedAt: {<br>        allowNull: false,<br>        type: Sequelize.DATE<br>      }<br>    });<br>  },<br>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.dropTable(&#39;Projects&#39;);<br>  }<br>};</pre><p>Perform the migration to create the Projects table in the Postgres database:</p><pre>npx sequelize-cli db:migrate</pre><p>Let’s create a seed file for Projects:</p><pre>npx sequelize-cli seed:generate --name projects</pre><p>You’ll see a new file in your /seeders subdirectory that ends with projects.js. Change the code in that file to the following:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Projects&#39;, [{<br>      title: &#39;Project 1&#39;,<br>      imageUrl: &#39;https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png&#39;,<br>      description: &#39;This project was built using Vanilla JavaScript, HTML, and CSS&#39;,<br>      userId: 1,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Project 2&#39;,<br>      imageUrl: &#39;https://www.stickpng.com/assets/images/584830f5cef1014c0b5e4aa1.png&#39;,<br>      description: &#39;This project was built using React &amp; a 3rd-party API.&#39;,<br>      userId: 3,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Project 3&#39;,<br>      imageUrl: &#39;https://expressjs.com/images/express-facebook-share.png&#39;,<br>      description: &#39;This project was built using Express &amp; React.&#39;,<br>      userId: 2,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Project 4&#39;,<br>      imageUrl: &#39;https://upload.wikimedia.org/wikipedia/commons/1/16/Ruby_on_Rails-logo.png&#39;,<br>      description: &#39;This project was built using Rails &amp; React.&#39;,<br>      userId: 1,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Projects&#39;, null, {});<br>  }<br>};</pre><p>Now we’ll run both seed files to add our users and our projects to the database:</p><pre>npx sequelize-cli db:seed:all</pre><p>Now let’s drop into psql to make sure the data exists on the database:</p><pre>psql projects_api_development<br>SELECT * FROM &quot;Users&quot; JOIN &quot;Projects&quot; ON &quot;Users&quot;.id = &quot;Projects&quot;.&quot;userId&quot;;</pre><h3>Setting up Express</h3><p>Great, our Sequelize project is ready to roll. Now we can incorporate Express and set up routes to serve our data. First, let’s install Express, along with <a href="https://nodemon.io/">nodemon</a> to monitor changes in our files and <a href="https://www.npmjs.com/package/body-parser">body-parser</a> to handle information from user requests:</p><pre>npm install express --save<br>npm install nodemon -D<br>npm install body-parser</pre><p>Now let’s set up the architecture by creating two new directories and three new files:</p><pre>mkdir routes controllers<br>touch server.js  routes/index.js controllers/index.js</pre><p>Now we’ll modify the package.json file to support nodemon. Also, we can facilitate development by creating a new command: npm db:reset. We’ll set this up to drop the database, create the database, run the migrations, and seed anew whenever we need!</p><pre>....<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;nodemon server.js&quot;,<br>    &quot;db:reset&quot;: &quot;npx sequelize-cli db:drop &amp;&amp; npx sequelize-cli db:create &amp;&amp; npx sequelize-cli db:migrate &amp;&amp; npx sequelize-cli db:seed:all&quot;<br>  },<br>....</pre><p>Now let’s start building our Express app. Inside the server.js file, add the following:</p><pre>const express = require(&#39;express&#39;);<br>const routes = require(&#39;./routes&#39;);<br>const bodyParser = require(&#39;body-parser&#39;)</pre><pre>const PORT = process.env.PORT || 3000;</pre><pre>const app = express();</pre><pre>app.use(bodyParser.json())</pre><pre>app.use(&#39;/api&#39;, routes);</pre><pre>app.listen(PORT, () =&gt; console.log(`Listening on port: ${PORT}`))</pre><p>Here we’ve created a basic Express server set to listen on port 3000. But rather than defining the routes in this file, we’ve added app.use(&#39;/api&#39;, routes) to refer any requests beginning with api to the index.js file in our /routes subdirectory.</p><blockquote>To learn more about basic Express setup with Sequelize, see:<br><a href="https://levelup.gitconnected.com/sequelize-cli-and-express-fb3ddefb9786"><strong>Sequelize CLI and Express</strong></a></blockquote><h3>Using Express Router with controllers</h3><p>We’ll start by setting up the root route. Open the ./routes/index.js file and add the following code:</p><pre>const { Router } = require(&#39;express&#39;);<br>const controllers = require(&#39;../controllers&#39;);<br>const router = Router();</pre><pre>router.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;This is root!&#39;))</pre><pre>module.exports = router</pre><p>Test the route:</p><pre>npm start</pre><p>Now open the root endpoint in your browser: <a href="http://localhost:3000/api/">http://localhost:3000/api/</a></p><p>Good, our Express app works, but now we need to make it deliver data from Sequelize. We’ll do this by creating a controller to handle all of our logic — our pathways for creating new users and projects, updating users, etc.</p><p>Open ./controllers/index.js and add the following:</p><pre>const { User } = require(&#39;../models&#39;);</pre><pre>const createUser = async (req, res) =&gt; {<br>    try {<br>        const user = await User.create(req.body);<br>        return res.status(201).json({<br>            user,<br>        });<br>    } catch (error) {<br>        return res.status(500).json({ error: error.message })<br>    }<br>}</pre><pre>module.exports = {<br>    createUser<br>}</pre><p>Here we’ve incorporated the User model we defined in Sequelize create a new database entry based on the information in the API request. To make this work, we’ll create a route on our server to connect the request with the controller:</p><p>In ./routes/index.js, add a new line after your “This is root!” route:</p><pre>router.post(&#39;/users&#39;, controllers.createUser)</pre><p>This directs POST requests at /api/users to the createUser function in our controller. To test it, you’ll need to use a REST client (like <a href="https://www.postman.com/">Postman</a> or <a href="https://insomnia.rest/">Insomnia</a>). Use the POST method to send the following JSON body to <a href="http://localhost:3000/api/users">http://localhost:3000/api/users</a>:</p><pre>{<br>  &quot;firstName&quot;: &quot;Jane&quot;,<br>  &quot;lastName&quot;: &quot;Smith&quot;,<br>  &quot;email&quot;: &quot;jane@smith.com&quot;,<br>  &quot;password&quot;: &quot;123456789&quot;<br>}</pre><p>Now we finally have a user who’s not named John! More importantly, we’ve used Router and a controller to deliver data from Sequelize to our API users. We can use the same strategy to connect any Sequelize query to an Express endpoint.</p><blockquote>To learn more about customizing Sequelize queries, see: <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314"><strong>Using the Sequelize CLI and Querying</strong></a></blockquote><p>Now let’s create another controller method to grab all the users from the database along with their associated projects. Make these changes to ./controllers/index.js:</p><pre>const { User, Project } = require(&#39;../models&#39;);</pre><pre>const createUser = async (req, res) =&gt; {<br>    try {<br>        const user = await User.create(req.body);<br>        return res.status(201).json({<br>            user,<br>        });<br>    } catch (error) {<br>        return res.status(500).json({ error: error.message })<br>    }<br>}</pre><pre>const getAllUsers = async (req, res) =&gt; {<br>    try {<br>        const users = await User.findAll({<br>            include: [<br>                {<br>                    model: Project<br>                }<br>            ]<br>        });<br>        return res.status(200).json({ users });<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>}</pre><pre>module.exports = {<br>    createUser,<br>    getAllUsers<br>}</pre><p>You’ll notice we’ve added the Project model to our requirement at the top, and the new getAllUsers function specifies that a user’s projects should be included. We’ve also added the new function to module.exports. Now we just need to add a route in ./routes/index.js to direct traffic toward this function:</p><pre>router.get(&#39;/users&#39;, controllers.getAllUsers)</pre><p>Test the route by opening <a href="http://localhost:3000/api/users">http://localhost:3000/api/users</a> in your browser or by doing a GET request in Postman.</p><p>Nice. Now let’s add the ability to find a specific user with their associated projects. Add the following function to ./controllers/index.js:</p><pre>const getUserById = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const user = await User.findOne({<br>            where: { id: id },<br>            include: [<br>                {<br>                    model: Project<br>                }<br>            ]<br>        });<br>        if (user) {<br>            return res.status(200).json({ user });<br>        }<br>        return res.status(404).send(&#39;User with the specified ID does not exists&#39;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>}</pre><p>Don’t forget to add getUserById to the export:</p><pre>module.exports = {<br>    createUser,<br>    getAllUsers,<br>    getUserById<br>}</pre><p>Now we’ll use the new function to make a new route in ./routes/index.js:</p><pre>router.get(&#39;/users/:id&#39;, controllers.getUserById)</pre><p>Here we’ve added a route parameter, :id. Our controller function pulls this info from req.params to find a specific user. Let’s test it at <a href="http://localhost:3000/api/users/2">http://localhost:3000/api/users/2</a>!</p><p>So we can now create users, show all users, and show a specific user. How about updating a user and deleting a user? Let’s add a new function for each in ./controllers/index.js:</p><pre>const updateUser = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const [updated] = await User.update(req.body, {<br>            where: { id: id }<br>        });<br>        if (updated) {<br>            const updatedUser = await User.findOne({ where: { id: id } });<br>            return res.status(200).json({ user: updatedUser });<br>        }<br>        throw new Error(&#39;User not found&#39;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>};</pre><pre>const deleteUser = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const deleted = await User.destroy({<br>            where: { id: id }<br>        });<br>        if (deleted) {<br>            return res.status(204).send(&quot;User deleted&quot;);<br>        }<br>        throw new Error(&quot;User not found&quot;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>};</pre><p>Make sure your exports are updated:</p><pre>module.exports = {<br>    createUser,<br>    getAllUsers,<br>    getUserById,<br>    updateUser,<br>    deleteUser<br>}</pre><p>Let’s add our routes in ./routes/index.js:</p><pre>router.put(&#39;/users/:id&#39;, controllers.updateUser)<br>router.delete(&#39;/users/:id&#39;, controllers.deleteUser)</pre><p>Now let’s test the update route by making a PUT request in Postman at <a href="http://localhost:3000/api/users/3">http://localhost:3000/api/users/3</a>. The request body should look something like this:</p><pre>{<br>    &quot;firstName&quot;: &quot;John&quot;,<br>    &quot;lastName&quot;: &quot;Smith&quot;,<br>    &quot;email&quot;: &quot;john.smith@smith.com&quot;,<br>    &quot;password&quot;: &quot;superPass1&quot;<br>}</pre><p>Finally, test delete with a DEL request at the same URL.</p><p>Now we’re down to only <em>two</em> Johns! More importantly, we’ve just built a full CRUD JSON API in Express, Sequelize, and Postgres using Express Router!</p><h3>Logging</h3><p>This is a good point to integrate better logging. Right now, if we check our terminal when we hit the <a href="http://localhost:3000/api/users/2">http://localhost:3000/api/users/2</a> endpoint, we’ll see the raw SQL that was executed. For debugging purposes and overall better logging let’s install an Express middleware called <a href="https://www.npmjs.com/package/morgan">morgan</a>:</p><pre>npm install morgan</pre><p>Add the following to your server.js file:</p><pre>const logger = require(&#39;morgan&#39;);<br>app.use(logger(&#39;dev&#39;))</pre><p>Let’s see the result:</p><pre>npm start<br>open <a href="http://localhost:3000/api/users/2">http://localhost:3000/api/users/2</a></pre><p>You should now see in your terminal something like this:</p><pre>GET /api/users/2 304 104.273 ms</pre><p>That’s morgan!</p><h3>Deploying to Heroku</h3><p>Now let’s deploy our app to <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">Heroku</a> to make a publicly accessible API.</p><p>Heroku will use package.json to build our app from the Git repository, so we need to update that file as follows:</p><pre>...<br>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;node server.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon server.js&quot;,<br>    &quot;db:reset&quot;: &quot;npx sequelize-cli db:drop &amp;&amp; npx sequelize-cli db:create &amp;&amp; npx sequelize-cli db:migrate &amp;&amp; npx sequelize-cli db:seed:all&quot;<br>  },<br>...</pre><p>Now, when Heroku starts your remote server with the npm start script, it will run your code in standard Node. (We can still use nodemon locally by running npm run dev.)</p><blockquote>You’ll need to install the Heroku CLI in your terminal for the following steps. <a href="https://devcenter.heroku.com/articles/heroku-cli"><strong>Find out how here.</strong></a></blockquote><p>Let’s use the Heroku CLI to set up a new app. Replace both instances of your-heroku-app-name in the code below with whatever name you like, then run these three commands in your terminal:</p><ol><li>heroku create <em>your-heroku-app-name</em></li><li>heroku buildpacks:set heroku/nodejs</li><li>heroku addons:create heroku-postgresql:hobby-dev --app=<em>your-heroku-app-name</em></li></ol><p>Now Heroku is prepared to build a Node.js app with a PostgreSQL database. Let’s commit our code to Git (make sure you’re on the master branch!) and upload the repository to Heroku:</p><ol><li>git status</li><li>git commit -am &quot;add any pending changes&quot;</li><li>git push heroku master</li></ol><p>Heroku will build a production version of the same app that we’ve been running in our local environment. Now we just need to tell Heroku to execute our migrations and seed files:</p><ol><li>heroku run npx sequelize-cli db:migrate</li><li>heroku run npx sequelize-cli db:seed:all</li></ol><blockquote>Having issues? Debug with the Heroku command heroku logs --tail to see what&#39;s happening on the Heroku server.</blockquote><p>Now you can test endpoints on your remote server by replacing “your-heroku-app-name” below with whatever name you used earlier:</p><ul><li>https://your-heroku-app-name.herokuapp.com/api/users</li><li>https://your-heroku-app-name.herokuapp.com/api/users/1</li></ul><p>There are those three Johns again! Try using Postman to create, update, and delete users the same way we did above.</p><p>Excellent! Now you can access your new Express API from anywhere on the planet. Next, try <a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">defining your own Sequelize associations</a>, making <a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">custom Sequelize queries</a>, and adding <a href="https://levelup.gitconnected.com/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">more robust seed data</a> — or ensure the reliability of your app by <a href="https://medium.com/@brunopgalvao/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59"><strong>building an Express API with unit testing</strong></a>!</p><blockquote>This article was co-authored with <a href="https://www.linkedin.com/in/jeremy-r-rose">Jeremy Rose</a>, a software engineer, editor, and writer based in New York City.</blockquote><h3>More info on Sequelize CLI and Express:</h3><ul><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">Getting Started with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">Using Sequelize CLI and Querying</a></li><li><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">Creating Sequelize Associations with Sequelize CLI</a></li><li><a href="https://levelup.gitconnected.com/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">Getting Started with Sequelize CLI using Faker</a></li><li><a href="https://medium.com/@brunopgalvao/sequelize-cli-and-express-fb3ddefb9786">Sequelize CLI and Express</a></li><li><a href="https://medium.com/@brunopgalvao/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59">Building an Express API with Sequelize CLI and Unit Testing!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963b6e274561" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561">Build an Express API with Sequelize CLI and Express Router</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Express API with Sequelize CLI and Unit Testing!]]></title>
            <link>https://levelup.gitconnected.com/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/882c6875ed59</guid>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sequelize-cli]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 19:14:11 GMT</pubDate>
            <atom:updated>2020-06-30T20:53:49.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*fygqfizATFjt6ALek2W1jg.png" /></figure><p>Unit testing is a useful habit for software developers to adopt. For any project whose code might grow more complex, unit testing can help ensure that the application’s core functionality is maintained even as changes are made.</p><p>Even for a relatively small-scale Node.js app, it’s possible to include unit testing by using npm packages like Jest and SuperTest. In this walkthrough, we’ll build a basic API using Sequelize and Express, then add unit tests to ensure that our CRUD endpoints remain intact.</p><h3>Creating the Sequelize application</h3><p>We’ll move as quickly as possible through our initial setup in order to get to our unit tests— but we’ll include notes along the way for those who want to know more about using the Sequelize CLI with Express.</p><p>Let’s start by installing Postgres, Sequelize, and the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> in a new project folder we’ll call express-api-unit-testing:</p><pre>mkdir express-api-unit-testing<br>cd express-api-unit-testing<br>git init<br>npm init -y &amp;&amp; npm i sequelize pg &amp;&amp; npm i --save-dev sequelize-cli</pre><p>Let’s also add a .gitignore file to ease deployment later:</p><pre>echo &quot;<br>/node_modules<br>.DS_Store<br>.env&quot; &gt;&gt; .gitignore</pre><p>Next we will initialize a Sequelize project, then open the directory in our code editor:</p><pre>npx sequelize-cli init<br>code .</pre><blockquote>To learn more about the Sequelize CLI commands below, see:<br><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6"><strong>Getting Started with Sequelize CLI</strong></a></blockquote><p>Let’s configure our Sequelize project to work with a Postgres database. Find config.json in the /config directory and change the code to look like this:</p><pre>{<br>  &quot;development&quot;: {<br>    &quot;database&quot;: &quot;wishlist_api_development&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;test&quot;: {<br>    &quot;database&quot;: &quot;wishlist_api_test&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;production&quot;: {<br>    &quot;use_env_variable&quot;: &quot;DATABASE_URL&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;,<br>    &quot;dialectOptions&quot;: {<br>      &quot;ssl&quot;: {<br>        &quot;rejectUnauthorized&quot;: false<br>      }<br>    }<br>  }<br>}</pre><blockquote>Note: For <em>production</em> we use <em>use_env_variable</em> and <em>DATABASE_URL</em>. We are going to deploy this app to <a href="https://www.heroku.com/">Heroku</a>. Heroku is smart enough to replace <em>DATABASE_URL</em> with the production database, which we’ll see in action late<em>r.</em></blockquote><p>Now we can tell Sequelize CLI to create the Postgres database:</p><pre>npx sequelize-cli db:create</pre><h3>Defining models and adding seed data</h3><p>Our demonstration app will associate users with items on a wishlist. Let’s start by creating a User model using the Sequelize CLI:</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string</pre><p>Running model:generate automatically creates both a model file and a migration with the attributes we’ve specified. Now we can execute the migration to create the Users table in our database:</p><pre>npx sequelize-cli db:migrate</pre><p>Now let’s create a seed file:</p><pre>npx sequelize-cli seed:generate --name users</pre><p>You will see a new file in the/seeders directory. In that file, paste the code below, which will create entries in your database for three users:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Users&#39;, [{<br>      firstName: &#39;Bruno&#39;,<br>      lastName: &#39;Doe&#39;,<br>      email: &#39;bruno@doe.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      firstName: &#39;Emre&#39;,<br>      lastName: &#39;Smith&#39;,<br>      email: &#39;emre@smith.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      firstName: &#39;John&#39;,<br>      lastName: &#39;Stone&#39;,<br>      email: &#39;john@stone.com&#39;,<br>      password: &#39;123456789&#39;,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Users&#39;, null, {});<br>  }<br>};</pre><p>In our API, each of these users can have many wishlist items. Let’s create an Item model to give these users something to wish for:</p><pre>npx sequelize-cli model:generate --name Item --attributes title:string,link:string,userId:integer</pre><p>Now we’ll create associations between the two models.</p><blockquote>To learn more about creating Sequelize associations, see:<br><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233"><strong>Creating Sequelize Associations with Sequelize CLI</strong></a></blockquote><p>First, find item.js in the /models subdirectory and replace the code with this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const Item = sequelize.define(&#39;Item&#39;, {<br>    title: DataTypes.STRING,<br>    link: DataTypes.STRING,<br>    userId: {<br>      type: DataTypes.INTEGER,<br>      references: {<br>        model: &#39;User&#39;,<br>        key: &#39;id&#39;,<br>        as: &#39;userId&#39;,<br>      }<br>    }<br>  }, {});<br>  Item.associate = function (models) {<br>    // associations can be defined here<br>    Item.belongsTo(models.User, {<br>      foreignKey: &#39;userId&#39;,<br>      onDelete: &#39;CASCADE&#39;<br>    })<br>  };<br>  return Item;<br>};</pre><p>Now find user.js in the the same directory and replace the code with this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const User = sequelize.define(&#39;User&#39;, {<br>    firstName: DataTypes.STRING,<br>    lastName: DataTypes.STRING,<br>    email: DataTypes.STRING,<br>    password: DataTypes.STRING<br>  }, {});<br>  User.associate = function(models) {<br>    // associations can be defined here<br>    User.hasMany(models.Item, {<br>      foreignKey: &#39;userId&#39;<br>    })<br>  };<br>  return User;<br>};</pre><p>Perform the migration to create the Items table in the Postgres database:</p><pre>npx sequelize-cli db:migrate</pre><p>Let’s create some items for our users to wish for:</p><pre>npx sequelize-cli seed:generate --name items</pre><p>You’ll see a new file in your /seeders subdirectory that ends with items.js. Change the code in that file to the following:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Items&#39;, [{<br>      title: &#39;Moped&#39;,<br>      link: &#39;https://detroitmopedworks.com&#39;,<br>      userId: 1,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;iPad Mini&#39;,<br>      link: &#39;https://www.apple.com/ipad-mini&#39;,<br>      userId: 3,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Electric Scooter&#39;,<br>      link: &#39;https://swagtron.com/electric-scooter&#39;,<br>      userId: 1,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Monitor&#39;,<br>      link: &#39;https://www.asus.com/us/Monitors/MB168B&#39;,<br>      userId: 2,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Items&#39;, null, {});<br>  }<br>};</pre><p>Now we’ll run both seed files to add our users and our wishlist items to the database:</p><pre>npx sequelize-cli db:seed:all</pre><p>Make sure the data exists on the database:</p><pre>psql wishlist_api_development<br>SELECT * FROM &quot;Users&quot; JOIN &quot;Items&quot; ON &quot;Users&quot;.id = &quot;Items&quot;.&quot;userId&quot;;</pre><h3>Setting up Express</h3><p>Great, our Sequelize project is ready to roll. Now we can incorporate Express and set up routes to serve our data. First, let’s install Express, along with <a href="https://nodemon.io/">nodemon</a> to monitor changes in our files and <a href="https://www.npmjs.com/package/body-parser">body-parser</a> to handle information from user requests:</p><pre>npm install express --save<br>npm install nodemon -D<br>npm install body-parser</pre><p>Now let’s set up the architecture by creating two new directories and three new files:</p><pre>mkdir routes controllers<br>touch server.js  routes/index.js controllers/index.js</pre><p>Now we’ll modify the package.json file to support nodemon. Also, we can facilitate development by creating a new command: npm run db:reset. We’ll set this up to drop the database, create the database, run the migrations, and seed anew whenever we need!</p><pre>....<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;nodemon server.js&quot;,<br>    &quot;db:reset&quot;: &quot;npx sequelize-cli db:drop &amp;&amp; npx sequelize-cli db:create &amp;&amp; npx sequelize-cli db:migrate &amp;&amp; npx sequelize-cli db:seed:all&quot;<br>  },<br>....</pre><p>Now let’s start building our Express app. Inside the server.js file, add the following:</p><pre>const express = require(&#39;express&#39;);<br>const routes = require(&#39;./routes&#39;);<br>const bodyParser = require(&#39;body-parser&#39;)</pre><pre>const PORT = process.env.PORT || 3000;</pre><pre>const app = express();</pre><pre>app.use(bodyParser.json())</pre><pre>app.use(&#39;/api&#39;, routes);</pre><pre>app.listen(PORT, () =&gt; console.log(`Listening on port: ${PORT}`))</pre><p>Here we’ve created a basic Express server set to listen on port 3000. But rather than defining the routes in this file, we’ve added app.use(&#39;/api&#39;, routes) to refer any requests beginning with api to the index.js file in our /routes subdirectory.</p><blockquote>To learn more about basic Express setup with Sequelize, see:<br><a href="https://levelup.gitconnected.com/sequelize-cli-and-express-fb3ddefb9786"><strong>Sequelize CLI and Express</strong></a></blockquote><h3>Express Router and controllers</h3><p>We’ll start by setting up the root route. Open the ./routes/index.js file and add the following code:</p><pre>const { Router } = require(&#39;express&#39;);<br>const controllers = require(&#39;../controllers&#39;);<br>const router = Router();</pre><pre>router.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;This is root!&#39;))</pre><pre>module.exports = router</pre><p>Test the route:</p><pre>npm start</pre><p>Now open the root endpoint in your browser: <a href="http://localhost:3000/api/">http://localhost:3000/api/</a></p><p>Good, our Express app works, but now we need to make it deliver data from Sequelize. We’ll do this by creating a controller to handle all of our logic — our pathways for creating new users and projects, updating users, etc.</p><blockquote>To learn more about using controllers with Sequelize and Express Router, see:<br><a href="https://levelup.gitconnected.com/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561"><strong>Build an Express API with Sequelize and Express Router</strong></a></blockquote><p>Now open ./controllers/index.js and add the following:</p><pre>const { User } = require(&#39;../models&#39;);</pre><pre>const createUser = async (req, res) =&gt; {<br>    try {<br>        const user = await User.create(req.body);<br>        return res.status(201).json({<br>            user,<br>        });<br>    } catch (error) {<br>        return res.status(500).json({ error: error.message })<br>    }<br>}</pre><pre>module.exports = {<br>    createUser<br>}</pre><p>Here we’ve incorporated the User model we defined in Sequelize create a new database entry based on the information in the API request. To make this work, we’ll create a route on our server to connect the request with the controller:</p><p>In ./routes/index.js, add a new line after your “This is root!” route:</p><pre>router.post(&#39;/users&#39;, controllers.createUser)</pre><p>This directs POST requests at /api/users to the createUser function in our controller. To test it, you’ll need to use a REST client (like <a href="https://www.postman.com/">Postman</a> or <a href="https://insomnia.rest/">Insomnia</a>). Use the POST method to send the following JSON body to <a href="http://localhost:3000/api/users">http://localhost:3000/api/users</a>:</p><pre>{<br>  &quot;firstName&quot;: &quot;Jane&quot;,<br>  &quot;lastName&quot;: &quot;Smith&quot;,<br>  &quot;email&quot;: &quot;jane@smith.com&quot;,<br>  &quot;password&quot;: &quot;123456789&quot;<br>}</pre><p>So now we’ve used Router and a controller to deliver data from Sequelize to our API users. We can use the same strategy to connect any Sequelize query to an Express endpoint.</p><blockquote>To learn more about customizing Sequelize queries, see: <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314"><strong>Using the Sequelize CLI and Querying</strong></a></blockquote><p>Let’s add controllers to perform four more tasks: get all users with their associated wishlist items, get a specific user and wishlist, update a user, and delete a user.</p><p>Replace what you currently have in ./controllers/index.js with the following:</p><pre>const { User, Item } = require(&#39;../models&#39;);</pre><pre>const createUser = async (req, res) =&gt; {<br>    try {<br>        const user = await User.create(req.body);<br>        return res.status(201).json({<br>            user,<br>        });<br>    } catch (error) {<br>        return res.status(500).json({ error: error.message })<br>    }<br>}</pre><pre>const getAllUsers = async (req, res) =&gt; {<br>    try {<br>        const users = await User.findAll({<br>            include: [<br>                {<br>                    model: Item<br>                }<br>            ]<br>        });<br>        return res.status(200).json({ users });<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>}</pre><pre>const getUserById = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const user = await User.findOne({<br>            where: { id: id },<br>            include: [<br>                {<br>                    model: Item<br>                }<br>            ]<br>        });<br>        if (user) {<br>            return res.status(200).json({ user });<br>        }<br>        return res.status(404).send(&#39;User with the specified ID does not exists&#39;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>}</pre><pre>const updateUser = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const [updated] = await User.update(req.body, {<br>            where: { id: id }<br>        });<br>        if (updated) {<br>            const updatedUser = await User.findOne({ where: { id: id } });<br>            return res.status(200).json({ user: updatedUser });<br>        }<br>        throw new Error(&#39;User not found&#39;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>};</pre><pre>const deleteUser = async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params;<br>        const deleted = await User.destroy({<br>            where: { id: id }<br>        });<br>        if (deleted) {<br>            return res.status(204).send(&quot;User deleted&quot;);<br>        }<br>        throw new Error(&quot;User not found&quot;);<br>    } catch (error) {<br>        return res.status(500).send(error.message);<br>    }<br>};</pre><pre>module.exports = {<br>    createUser,<br>    getAllUsers,<br>    getUserById,<br>    updateUser,<br>    deleteUser<br>}</pre><p>We’ll also set up each route to hit the correct controller. Change the /routes/index.js file to look like this:</p><pre>const { Router } = require(&#39;express&#39;);<br>const controllers = require(&#39;../controllers&#39;)<br>const router = Router();</pre><pre>router.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;This is root!&#39;))</pre><pre>router.post(&#39;/users&#39;, controllers.createUser)<br>router.get(&#39;/users&#39;, controllers.getAllUsers)<br>router.get(&#39;/users/:id&#39;, controllers.getUserById)<br>router.put(&#39;/users/:id&#39;, controllers.updateUser)<br>router.delete(&#39;/users/:id&#39;, controllers.deleteUser)</pre><pre>module.exports = router;</pre><p>Test some of these endpoints making a GET, POST, PUT, or DELETE request in Postman along with the appropriate request body for each endpoint. The body for a PUT request at <a href="http://localhost:3000/users/3">http://localhost:3000/users/3</a>, for instance, might look something like this:</p><pre>{<br>    &quot;firstName&quot;: &quot;Johnny&quot;,<br>    &quot;lastName&quot;: &quot;Stone&quot;,<br>    &quot;email&quot;: &quot;john.e@stone.com&quot;<br>}</pre><p>If your manual testing goes well, it’s time to start building automated unit tests!</p><h3>Logging</h3><p>First, though, this is a good point to integrate better logging. Right now, if we check our terminal when we hit the <a href="http://localhost:3000/api/users/2">http://localhost:3000/api/users/2</a> endpoint, we’ll see the raw SQL that was executed. For debugging purposes and overall better logging let’s install an Express middleware called <a href="https://www.npmjs.com/package/morgan">morgan</a>:</p><pre>npm install morgan</pre><p>Modify your server.js file to use Morgan (and also to add module.exports = app, which we will be using later in testing):</p><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const logger = require(&#39;morgan&#39;);</pre><pre>const routes = require(&#39;./routes&#39;);</pre><pre>const PORT = process.env.PORT || 3000;</pre><pre>const app = express();<br>app.use(bodyParser.json())<br>app.use(logger(&#39;dev&#39;))</pre><pre>app.use(&#39;/api&#39;, routes);</pre><pre>app.listen(PORT, () =&gt; console.log(`Listening on port: ${PORT}`))</pre><pre>module.exports = app</pre><p>Let’s see the result:</p><pre>npm start<br>open <a href="http://localhost:3000/api/users/2">http://localhost:3000/api/users/2</a></pre><p>You should now see in your terminal something like this:</p><pre>GET /api/users/2 304 104.273 ms</pre><p>That’s morgan!</p><h3>Unit Testing</h3><p>Now we’re going to configure our Express JSON API for unit tests. Let’s install <a href="https://jestjs.io/">Jest</a> — a delightful JavaScript testing framework with a focus on simplicity:</p><pre>npm install jest --save-dev</pre><p>We are also going to use <a href="https://github.com/visionmedia/supertest#readme">SuperTest</a> for testing our HTTP endpoints on our Express API:</p><pre>npm install supertest --save-dev</pre><p>We need to make two changes in package.json to configure Jest. First, under the &quot;scripts&quot; attribute, let’s edit our test command to use Jest:</p><pre>...<br>&quot;test&quot;: &quot;jest&quot;,<br>...</pre><p>We need Jest to ignore our ./node_modules folder, so we also need to add this snippet of code:</p><pre>....<br> &quot;jest&quot;: {<br>    &quot;testEnvironment&quot;: &quot;node&quot;,<br>    &quot;coveragePathIgnorePatterns&quot;: [<br>      &quot;/node_modules/&quot;<br>    ]<br>  },<br>....</pre><p>Great! Let’s write a simple test to make sure our setup works. First, we’ll make a new directory for our tests, then we’ll make a file called base.test.js:</p><pre>mkdir tests<br>touch tests/base.test.js</pre><p>Now add the following code in base.test.js to create a test that will test whether 1 + 1 = 2:</p><pre>describe(&#39;Initial Test&#39;, () =&gt; {<br>  it(&#39;should test that 1 + 1 === 2&#39;, () =&gt; {<br>    expect(1+1).toBe(2)<br>  })<br>})</pre><p>Take a look at the syntax here. We pass strings to give the test a title and to describe what it does. Then, if the expression passed to expect() evaluates to the value within .toBe(), the test will pass. Let’s make sure our setup works:</p><pre>npm test</pre><p>OK, that’s a relief! Jest checked it out for us, and it turns out that1+1 <em>does</em> equal 2. Soon we’ll start putting Jest to practical use.</p><h3>Setting up a test environment</h3><p>First, we need to set up our test scripts to use a test database — it wouldn’t be a good idea to let our tests manipulate our real data. We’ll arrange this by using an npm package called <a href="https://www.npmjs.com/package/cross-env">cross-env</a>:</p><pre>npm install cross-env --save-dev</pre><p>Cross-env lets us pass environment variables in npm scripts, which in this case we’ll use to specify a test environment. Let’s again configure the “scripts” section of our package.json to do this:</p><pre>&quot;test&quot;: &quot;cross-env NODE_ENV=test jest --testTimeout=10000&quot;,<br>&quot;pretest&quot;: &quot;cross-env NODE_ENV=test npm run db:reset&quot;,<br>&quot;db:create:test&quot;: &quot;cross-env NODE_ENV=test npx sequelize-cli db:create&quot;,</pre><p>Try it.</p><pre>npm run db:create:test<br>npm test</pre><p>The pretest script builds your test database afresh before running the tests — and using NODE_ENV=test lets our script do all that without altering our normal database. In addition to all that, your terminal should also show that our base test in Jest has passed.</p><h3>Writing tests with Jest and SuperTest</h3><p>Time to write our first route test. Let’s create the a test file for routes:</p><pre>touch tests/routes.test.js</pre><p>We are going to write this using the Jest framework and call the HTTP methods using SuperTest.</p><p>Let’s test the /api/users endpoint. When we do a GET request to that endpoint we should get back a list of all users in the database, right? Open up tests/routes.test.js and add this code:</p><pre>const request = require(&#39;supertest&#39;)<br>const app = require(&#39;../server.js&#39;)</pre><pre>describe(&#39;User API&#39;, () =&gt; {<br>    it(&#39;should show all users&#39;, async () =&gt; {<br>        const res = await request(app).get(&#39;/api/users&#39;)<br>        expect(res.statusCode).toEqual(200)<br>        expect(res.body).toHaveProperty(&#39;users&#39;)<br>    }),<br>})</pre><p>Test it!</p><pre>npm test</pre><p>You should see two passing tests now in two test suites.</p><p>Next, we’ll add another test to the same User API test suite, this one for the /api/users/3 endpoint. At this endpoint, a GET request should return a specific user from the database. In tests/routes.test.js, add the following just below the previous test:</p><pre>    it(&#39;should show a user&#39;, async () =&gt; {<br>        const res = await request(app).get(&#39;/api/users/3&#39;)<br>        expect(res.statusCode).toEqual(200)<br>        expect(res.body).toHaveProperty(&#39;user&#39;)<br>    }),</pre><p>Test it!</p><pre>npm test</pre><p>We can write more tests for other aspects of our API. The code below includes tests for creating, updating and deleting users in our app:</p><pre>const request = require(&#39;supertest&#39;)<br>const app = require(&#39;../server.js&#39;)</pre><pre>describe(&#39;User API&#39;, () =&gt; {<br>    it(&#39;should show all users&#39;, async () =&gt; {<br>        const res = await request(app).get(&#39;/api/users&#39;)<br>        expect(res.statusCode).toEqual(200)<br>        expect(res.body).toHaveProperty(&#39;users&#39;)<br>    }),</pre><pre>    it(&#39;should show a user&#39;, async () =&gt; {<br>        const res = await request(app).get(&#39;/api/users/3&#39;)<br>        expect(res.statusCode).toEqual(200)<br>        expect(res.body).toHaveProperty(&#39;user&#39;)<br>    }),</pre><pre>    it(&#39;should create a new user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .post(&#39;/api/users&#39;)<br>            .send({<br>                firstName: &#39;Bob&#39;,<br>                lastName: &#39;Doe&#39;,<br>                email: &#39;bob@doe.com&#39;,<br>                password: &#39;12345678&#39;<br>            })<br>        expect(res.statusCode).toEqual(201)<br>        expect(res.body).toHaveProperty(&#39;user&#39;)<br>    }),</pre><pre>    it(&#39;should update a user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .put(&#39;/api/users/3&#39;)<br>            .send({<br>                firstName: &#39;Bob&#39;,<br>                lastName: &#39;Smith&#39;,<br>                email: &#39;bob@doe.com&#39;,<br>                password: &#39;abc123&#39;<br>            })<br>        expect(res.statusCode).toEqual(200)<br>        expect(res.body).toHaveProperty(&#39;user&#39;)<br>    }),</pre><pre>    it(&#39;should delete a user&#39;, async () =&gt; {<br>        const res = await request(app)<br>            .del(&#39;/api/users/3&#39;)<br>        expect(res.statusCode).toEqual(204)<br>    })<br>})</pre><p>You’ll see that the new tests use the .post(), .put(), and .del() methods, and that the body of a test request can be defined within .send().</p><blockquote>Each of our example tests uses Jest’s .toEqual() and/or .toHaveProperty() methods. To see other Jest “matchers,” <a href="https://jestjs.io/docs/en/expect"><strong>check out the Jest documentation</strong></a>.</blockquote><p>Run the tests:</p><pre>npm test</pre><p>You should see six passing tests in two suites. We now have test coverage for our Express API!</p><blockquote>This article was co-authored with <a href="https://www.linkedin.com/in/jeremy-r-rose">Jeremy Rose</a>, a software engineer, editor, and writer based in New York City.</blockquote><h3>More info on Sequelize CLI and Express:</h3><ul><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">Getting Started with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">Using Sequelize CLI and Querying</a></li><li><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">Creating Sequelize Associations with Sequelize CLI</a></li><li><a href="https://levelup.gitconnected.com/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">Getting Started with Sequelize CLI using Faker</a></li><li><a href="https://medium.com/@brunopgalvao/sequelize-cli-and-express-fb3ddefb9786">Sequelize CLI and Express</a></li><li><a href="https://levelup.gitconnected.com/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561">Building an Express API with Sequelize CLI and Express Router</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=882c6875ed59" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59">Building an Express API with Sequelize CLI and Unit Testing!</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequelize CLI and Express]]></title>
            <link>https://levelup.gitconnected.com/sequelize-cli-and-express-fb3ddefb9786?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb3ddefb9786</guid>
            <category><![CDATA[sequelize-cli]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 19:13:32 GMT</pubDate>
            <atom:updated>2020-06-19T15:15:26.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*fygqfizATFjt6ALek2W1jg.png" /></figure><p><a href="http://sequelizejs.com/">Sequelize</a> is a popular, easy-to-use JavaScript object relational mapping (ORM) tool that works with SQL databases. If you’re comfortable <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314">querying your database using Sequelize models</a>, it’s fairly straightforward to tie Sequelize in with <a href="https://expressjs.com/">Express</a> to serve your data from a Node.js app.</p><p>In this walkthrough, we’ll start a Sequelize project from scratch, then incorporate Express to build basic routes that will deliver the information from your database.</p><p>Let’s start by installing Postgres, Sequelize, and the Sequelize CLI in a new project folder:</p><pre>mkdir express-sequelize-api<br>cd express-sequelize-api<br>npm init -y &amp;&amp; npm install sequelize pg &amp;&amp;  npm install --save-dev sequelize-cli</pre><p>Next we will initialize a Sequelize project, then open it in our code editor:</p><pre>npx sequelize-cli init<br>code .</pre><blockquote>To learn more about any of the Sequelize CLI commands below, see:<br><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6"><strong>Getting Started with Sequelize CLI</strong></a></blockquote><p>Let’s configure our Sequelize project to work with Postgres. Find config.json in the /config directory and make sure the development section looks like this:</p><pre>&quot;development&quot;: {<br>    &quot;database&quot;: &quot;products_development&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  }</pre><p>Cool, now we can tell the Sequelize CLI to create the database:</p><pre>npx sequelize-cli db:create</pre><p>Next we will create a Product model:</p><pre>npx sequelize-cli model:generate --name Product --attributes title:string,description:string,price:integer</pre><p>Running model:generate automatically creates both a model file and a migration with the attributes we’ve specified. For now, you won’t need to worry about (or edit) these in order to make our simple Express app below.</p><blockquote>Check out the other data types you can use with Sequelize: <a href="https://sequelize.org/master/manual/data-types.html">https://sequelize.org/master/manual/data-types.html</a></blockquote><p>Now we’ll execute our migration to create the Products table in our database:</p><pre>npx sequelize-cli db:migrate</pre><p>Now let’s create a seed file:</p><pre>npx sequelize-cli seed:generate --name products</pre><p>You will see a new file in the/seeders directory. In that file, paste the code below, which will create an entry in your database for each of the following irresistible products:</p><pre>&#39;use strict&#39;;</pre><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Products&#39;, [{<br>      title: &#39;Apple AirPods&#39;,<br>      description: &quot;https://www.apple.com/airpods&quot;,<br>      price: 199,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Apple iPhone Pro&#39;,<br>      description: &quot;https://www.apple.com/iphone-11-pro&quot;,<br>      price: 1000,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Apple Watch&#39;,<br>      description: &quot;https://www.apple.com/watch&quot;,<br>      price: 499,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Vespa Primavera&#39;,<br>      description: &quot;https://www.vespa.com/us_EN/vespa-models/primavera.html&quot;,<br>      price: 3000,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;New Balance 574 Core&#39;,<br>      description: &quot;https://www.newbalance.com/pd/574-core/ML574-EG.html&quot;,<br>      price: 84,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Tribe Messenger Bike 004&#39;,<br>      description: &quot;https://tribebicycles.com/collections/messenger-series/products/mess-004-tx&quot;,<br>      price: 675,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    },<br>    {<br>      title: &#39;Stumptown Hair Bender Coffee&#39;,<br>      description: &quot;https://www.stumptowncoffee.com/products/hair-bender&quot;,<br>      price: 16,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Products&#39;, null, {});<br>  }<br>};</pre><p>Once we’ve saved our seed file, let’s execute it:</p><pre>npx sequelize-cli db:seed:all</pre><p>Drop into psql and query the database to see what’s in your Products table:</p><pre>psql products_development<br>SELECT * FROM &quot;Products&quot;;</pre><p>You should see a stylish Vespa, some strong coffee, and a few Apple products, among other things. Great!</p><h3>Setting up Express</h3><p>Now that our database is set up, let’s incorporate Express to deliver these items via a Node.js server. Express is a highly customizable framework with a lot of capabilities, but for this example we’ll just quickly set up a few basic routes.</p><p>First, let’s install Express in our project directory and create a file to hold our server code:</p><pre>npm install express<br>touch server.js</pre><p>Express doesn’t require much configuration to get up and running. In your server.js file, just add the following:</p><pre>const express = require(&#39;express&#39;)<br>const PORT = process.env.PORT || 3000</pre><pre>const app = express()</pre><pre>app.listen(PORT, () =&gt; {<br>  console.log(`Express server listening on port ${PORT}`)<br>});</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&quot;This is root!&quot;)<br>})</pre><p>The first line pulls in the Express library, the second sets a default port (3000), and the third line fires up Express. Now app refers to your running Express app, and we can use methods like .listen() and .get() to tell it what to do!</p><p>Now fire up your app…</p><pre>node server.js</pre><p>…and open localhost:3000 in your web browser. You should see “This is root!” — that’s because we used app.listen() in our code to listen at that port, and we used app.get() to set up a route at &#39;/&#39;. (Press ctrl + c in your terminal to exit.)</p><h3>Using Sequelize with Express</h3><p>Awesome! Now we can connect our server to Sequelize. First, we need to introduce our Product model from within the /models folder. Add this line near the top of server.js:</p><pre>const { Product } = require(&#39;./models&#39;)</pre><p>Now we can create a route to show our entire list of products. We’ll use app.get() to set a route at &#39;/products&#39; and use our Sequelize model’s .findAll() method to return every Product:</p><pre>app.get(&#39;/products&#39;, async (req, res) =&gt; {<br>    const products = await Product.findAll()<br>    res.json(products)<br>})</pre><p>Restart the server by typing node server.js in your terminal, then test the route in your browser by going to <a href="http://localhost:3000/products">http://localhost:3000/products</a>. You should see a JSON response that includes every object, from the Apple Watch to the messenger bike.</p><p>OK, great! But what if we would like to see a specific product? Let’s say we navigate to <a href="http://localhost:3000/products/2">http://localhost:3000/products/2</a> in the browser. We can make our API respond with only the product whose id is 2 — and to do this we’ll use thereq.params object in Express:</p><pre>app.get(&#39;/products/:id&#39;, async (req, res) =&gt; {<br>  const { id } = req.params<br>  const product = await Product.findById(id)<br>  res.json(product)<br>})</pre><p><a href="https://expressjs.com/en/api.html#req">The </a><a href="https://expressjs.com/en/api.html#req">req object</a> in Express represents the HTTP request from the user. The req.params property includes the parameters we named in our route — these parameters are set up with a colon, like :id in &#39;/products/:id&#39; above. With req.params.id, we can use Sequelize’s .findById() method to get only the object whose id matches our URL.</p><p>OK, but what if the id doesn’t exist in the database? Currently, our user will get a JSON response that just says null. We can send a more useful error message by using a try/catch block:</p><pre>app.get(&#39;/products/:id&#39;, async (req, res) =&gt; {<br>    try {<br>        const { id } = req.params<br>        const product = await Product.findByPk(id)<br>        if (!product) throw Error(&#39;Product not found&#39;)<br>        res.json(product)<br>    } catch (e) {<br>        console.log(e)<br>        res.send(&#39;Product not found!&#39;)<br>    }<br>})</pre><p>Does it work? Restart the server and test the route.</p><pre>node server.js</pre><p>Open <a href="http://localhost:3000/products/2">http://localhost:3000/products/2</a> in your browser. Hey, it’s an iPhone! (You can also test the error handling by navigating to /products/987654321.)</p><h3>Going further with Express and Sequelize</h3><p>Now you know how to define endpoints in Express that deliver data from your database via a simple Sequelize model — and you can expand your project by using <a href="https://expressjs.com/en/starter/basic-routing.html">other Express request methods</a> with different Sequelize queries.</p><p>But when you’re tinkering with your Express project, restarting the server with every change can be a pain. Let’s fix this by installing <a href="https://nodemon.io/">nodemon</a>!</p><pre>npm install nodemon --save-dev</pre><p>Modify your package.json file:</p><pre>....<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;start&quot;: &quot;nodemon server.js&quot;<br>  },<br>....</pre><p>Now when you run npm start from your terminal, nodemon will watch for changes to your JavaScript files and automatically restart your server — so you won’t have to keep going back to your terminal while you’re designing new routes <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314"><strong>using other Sequelize querying methods</strong></a><strong>!</strong></p><blockquote>This article was co-authored with <a href="https://www.linkedin.com/in/jeremy-r-rose">Jeremy Rose</a>, a software engineer, editor, and writer based in New York City.</blockquote><h3>More info on Sequelize CLI:</h3><ul><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">Getting Started with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">Using Sequelize CLI and Querying</a></li><li><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">Creating Sequelize Associations with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">Getting Started with Sequelize CLI using Faker</a></li><li><a href="https://medium.com/@brunopgalvao/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561">Build an Express API with Sequelize CLI and Express Router</a></li><li><a href="https://medium.com/@brunopgalvao/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59">Building an Express API with Sequelize CLI and Unit Testing!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb3ddefb9786" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/sequelize-cli-and-express-fb3ddefb9786">Sequelize CLI and Express</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Sequelize Associations with the Sequelize CLI tool]]></title>
            <link>https://levelup.gitconnected.com/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/d83caa902233</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sequelize-cli]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 19:12:41 GMT</pubDate>
            <atom:updated>2020-06-19T15:15:35.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Sequelize Associations with the Sequelize CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*fygqfizATFjt6ALek2W1jg.png" /></figure><p><a href="http://sequelizejs.com/">Sequelize</a> is a popular, easy-to-use JavaScript object relational mapping (ORM) tool that works with SQL databases. It’s fairly straightforward to <a href="https://levelup.gitconnected.com/getting-started-with-sequelize-cli-c33c797f05c6">start a new project using the Sequelize CLI</a>, but to truly take advantage of Sequelize’s capabilities, you’ll want to define relationships between your models.</p><p>In this walkthrough, we’ll set up a Sequelize project to assign tasks to particular users. We’ll use associations to define that relationship, then explore ways to query the database based on those associations.</p><p>Let’s start by installing Postgres, Sequelize, and the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> in a new project folder:</p><pre>mkdir sequelize-associations<br>cd sequelize-associations<br>npm init -y<br>npm install sequelize pg<br>npm install --save-dev sequelize-cli</pre><p>Next, let’s initialize a Sequelize project, then open the whole directory in our code editor:</p><pre>npx sequelize-cli init<br>code .</pre><blockquote>To learn more about any of the Sequelize CLI commands below, see:<br><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6"><strong>Getting Started with Sequelize CLI</strong></a></blockquote><p>Let’s configure our Sequelize project to work with Postgres. Find config.json in the /config directory and replace what’s there with this code:</p><pre>{<br>  &quot;development&quot;: {<br>    &quot;database&quot;: &quot;sequelize_associations_development&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;test&quot;: {<br>    &quot;database&quot;: &quot;sequelize_associations_test&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;production&quot;: {<br>    &quot;database&quot;: &quot;sequelize_associations_production&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  }<br>}</pre><p>Cool, now we can tell Sequelize to create the database:</p><pre>npx sequelize-cli db:create</pre><p>Next we will create a User model from the command line:</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string</pre><p>Running model:generate automatically creates both a model file and a migration with the attributes we’ve specified. You can find these files within your project directory, but there’s no need to change them right now. (Later, we’ll edit the model file to define our associations.)</p><p>Now we’ll execute our migration to create the Users table in our database:</p><pre>npx sequelize-cli db:migrate</pre><p>Now let’s create a seed file:</p><pre>npx sequelize-cli seed:generate --name user</pre><p>You will see a new file in /seeders. In that file, paste the following code to create a “John Doe” demo user:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Users&#39;, [{<br>        firstName: &#39;John&#39;,<br>        lastName: &#39;Doe&#39;,<br>        email: &#39;demo@demo.com&#39;,<br>        password: &#39;$321!pass!123$&#39;,<br>        createdAt: new Date(),<br>        updatedAt: new Date()<br>      }], {});<br>  },</pre><pre>down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Users&#39;, null, {});<br>  }<br>};</pre><p>Once we’ve saved our seed file, let’s execute it:</p><pre>npx sequelize-cli db:seed:all</pre><p>Drop into psql and query the database to see the Users table:</p><pre>psql sequelize_associations_development<br>SELECT * FROM &quot;Users&quot;;</pre><h3>Defining associations</h3><p>Great! We’ve got a working User model, but our John Doe seems a little bored. Let’s give John something to do by creating a Task model:</p><pre>npx sequelize-cli model:generate --name Task --attributes title:string,userId:integer</pre><p>Just as with the User model above, this Sequelize CLI command will create both a model file and a migration based on the attributes we specified. But this time, we’ll need to edit both in order to tie our models together.</p><p>First, find task.js in the /models subdirectory within your project directory. This is the Sequelize model for tasks, and you’ll see that the sequelize.define() method sets up title and userId as attributes, just as we specified above.</p><p>Below that, you’ll see Task.associate. It’s currently empty, but this is where we’ll actually tie each task to a userId. Edit your file to look like this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const Task = sequelize.define(&#39;Task&#39;, {<br>    title: DataTypes.STRING,<br>    userId: DataTypes.INTEGER<br>  }, {});<br>  Task.associate = function(models) {<br>    // associations can be defined here<br>    Task.belongsTo(models.User, {<br>      foreignKey: &#39;userId&#39;,<br>      onDelete: &#39;CASCADE&#39;<br>    })<br>  };<br>  return Task;<br>};</pre><p>What do those changes do? Task.belongsTo() <a href="https://sequelize.org/master/class/lib/model.js~Model.html#static-method-belongsTo">sets up a “belongs to” relationship</a> with the User model, meaning that each task will be associated with a specific user.</p><p>We do this by setting userId as a “foreign key,” which means it refers to a key in another model. In our model, tasks must belong to a user, so userId will correspond to theid in a particular User entry. (The onDelete: &#39;CASCADE&#39; configures our model so that if a user is deleted, the user’s tasks will be deleted too.)</p><p>We also need to change our User model to reflect the other side of this relationship. Find user.js and change the section under User.associate so that your file looks like this:</p><pre>module.exports = (sequelize, DataTypes) =&gt; {<br>  const User = sequelize.define(&#39;User&#39;, {<br>    firstName: DataTypes.STRING,<br>    lastName: DataTypes.STRING,<br>    password: DataTypes.STRING,<br>    email: DataTypes.STRING<br>  }, {});<br>  User.associate = function(models) {<br>    // associations can be defined here<br>    User.hasMany(models.Task, {<br>      foreignKey: &#39;userId&#39;,<br>    })<br>  };<br>  return User;<br>};</pre><p>For this model, we’ve set up a “has many” relationship, meaning a user can have multiple tasks. In the .hasMany() method, the foreignKey option is set to the name of the key on the <em>other</em> table. In other words, when theuserId on a task is the same as the id of a user, we have a match.</p><p>We still have to make one more change to set up our relationship in the database. In your project’s/migrations folder, you should see a file whose name ends with create-task.js. Change the object labeled userId so that your file looks like the code below:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.createTable(&#39;Tasks&#39;, {<br>      id: {<br>        allowNull: false,<br>        autoIncrement: true,<br>        primaryKey: true,<br>        type: Sequelize.INTEGER<br>      },<br>      title: {<br>        type: Sequelize.STRING<br>      },<br>      userId: {<br>        type: Sequelize.INTEGER,<br>        onDelete: &#39;CASCADE&#39;,<br>        references: {<br>          model: &#39;Users&#39;,<br>          key: &#39;id&#39;,<br>          as: &#39;userId&#39;,<br>        }<br>      },<br>      createdAt: {<br>        allowNull: false,<br>        type: Sequelize.DATE<br>      },<br>      updatedAt: {<br>        allowNull: false,<br>        type: Sequelize.DATE<br>      }<br>    });<br>  },<br>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.dropTable(&#39;Tasks&#39;);<br>  }<br>};</pre><p>The references section will set up the Tasks table in our database to reflect the same relationships we described above. Now we can run our migration:</p><pre>npx sequelize-cli db:migrate</pre><p>Now our John Doe is ready to take on tasks — but John still doesn’t have any actual tasks assigned. Let’s create a task seed file:</p><pre>npx sequelize-cli seed:generate --name task</pre><p>Find the newly generated seed file and paste in the following to create a task:</p><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Tasks&#39;, [{<br>      title: &#39;Build an app&#39;,<br>      userId: 1,<br>      createdAt: new Date(),<br>      updatedAt: new Date()<br>    }], {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Tasks&#39;, null, {});<br>  }<br>};</pre><p>We’ll set userId to 1 so that the task will belong to the user we created earlier. Now we can populate the database.</p><pre>npx sequelize-cli db:seed:all</pre><p>Test the database:</p><pre>psql sequelize_associations_development<br>SELECT * FROM &quot;Users&quot; JOIN &quot;Tasks&quot; ON &quot;Tasks&quot;.&quot;userId&quot; = &quot;Users&quot;.id;</pre><h3>Querying via Sequelize</h3><p>Now we can query our database for information based on these associations — and through Sequelize, we can do it with JavaScript, which makes it easy to incorporate with a Node.js application. Let’s create a file to hold our queries:</p><pre>touch query.js</pre><p>Paste the code below into your new file:</p><pre>const { User, Task } = require(&#39;./models&#39;)<br>const Sequelize = require(&#39;sequelize&#39;);<br>const Op = Sequelize.Op<br><br>// Find all users with their associated tasks<br>// Raw SQL: SELECT * FROM &quot;Users&quot; JOIN &quot;Tasks&quot; ON &quot;Tasks&quot;.&quot;userId&quot; = &quot;Users&quot;.id;<br><br>const findAllWithTasks = async () =&gt; {<br>    const users = await User.findAll({<br>        include: [{<br>            model: Task<br>        }]<br>    });<br>    console.log(&quot;All users with their associated tasks:&quot;, JSON.stringify(users, null, 4));<br>}<br><br>const run = async () =&gt; {<br>    await findAllWithTasks()<br>    await process.exit()<br>}<br><br>run()</pre><p>The first three lines above import our User and Task models, along with Sequelize. After that, we include a query function that returns every User along with that user’s associated tasks.</p><p>Sequelize’s .findAll() method accepts options as a JavaScript object. Above, we used the include option to <a href="https://sequelize.org/master/manual/eager-loading.html">take advantage of “eager loading” </a>— querying data from multiple models at the same time. With this option, Sequelize will return a JavaScript object that includes each User with all associated Task instances as nested objects.</p><p>Let’s run our query file to see this in action:</p><pre>node query.js</pre><p>Now it’s clear that our John Doe has a project to work on! We can use the same method to include the User when our query finds a Task. Paste the following code into query.js:</p><pre>// Find a task with its associated user<br>// Raw SQL: SELECT * FROM &quot;Tasks&quot; JOIN &quot;Users&quot; ON &quot;Users&quot;.&quot;id&quot; = &quot;Tasks&quot;.&quot;userId&quot;;<br><br>const findTasksWithUser = async () =&gt; {<br>    const tasks = await Task.findAll({<br>        include: [{<br>            model: User<br>        }]<br>    });<br>    console.log(&quot;All tasks with their associated user:&quot;, JSON.stringify(tasks, null, 4));<br>}</pre><p>Modify const run at the bottom of query.js by adding a line to call findTasksWithUser(). Now run your file again in Node — each Task should include info for the User it belongs to.</p><blockquote>The queries in this walkthrough make use of the .findAll() method. To learn more about other Sequelize queries, see: <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314"><strong>Using the Sequelize CLI and Querying</strong></a></blockquote><p>You can also include other options alongside include to make more specific queries. For example, below we’ll use the where option to find only the users named John while still returning the associated tasks for each:</p><pre>// Find all users named John with their associated tasks<br>// Raw SQL: SELECT * FROM &quot;Users&quot; WHERE firstName = &quot;John&quot; JOIN tasks ON &quot;Tasks&quot;.&quot;userId&quot; = &quot;Users&quot;.id;</pre><pre>const findAllJohnsWithTasks = async () =&gt; {<br>    const users = await User.findAll({<br>        where: { firstName: &quot;John&quot; },<br>        include: [{<br>            model: Task<br>        }]<br>    });<br>    console.log(&quot;All users named John with their associated tasks:&quot;, JSON.stringify(users, null, 4));<br>}</pre><p>Paste the above into your query.js and change const run to call findAllJohnsWithTasks() to try it out.</p><p>Now that you know how to use model associations in Sequelize, you can design your application to deliver the nested data you need. For your next step, you might decide to <a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe"><strong>include more robust seed data using Faker</strong></a> or <a href="https://medium.com/@brunopgalvao/sequelize-cli-and-express-fb3ddefb9786"><strong>integrate your Sequelize application with Express</strong></a> to create a Node.js server!</p><blockquote>This article was co-authored with <a href="https://www.linkedin.com/in/jeremy-r-rose">Jeremy Rose</a>, a software engineer, editor, and writer based in New York City.</blockquote><h3>More info on Sequelize CLI:</h3><ul><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">Getting Started with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">Using Sequelize CLI and Querying</a></li><li><a href="https://medium.com/@brunopgalvao/sequelize-cli-and-express-fb3ddefb9786">Sequelize CLI and Express</a></li><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">Getting Started with Sequelize CLI using Faker</a></li><li><a href="https://medium.com/@brunopgalvao/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561">Build an Express API with Sequelize CLI and Express Router</a></li><li><a href="https://medium.com/@brunopgalvao/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59">Building an Express API with Sequelize CLI and Unit Testing!</a></li></ul><h3>Resources</h3><ul><li><a href="https://sequelize.org/master/manual/associations.html">https://sequelize.org/master/manual/associations.html</a></li><li><a href="https://sequelize.org/master/manual/querying.html">https://sequelize.org/master/manual/querying.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83caa902233" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">Creating Sequelize Associations with the Sequelize CLI tool</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Sequelize CLI using Faker]]></title>
            <link>https://levelup.gitconnected.com/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe?source=rss-ddc99afb7ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/824b3f4c4cfe</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Bruno Galvao]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 19:10:52 GMT</pubDate>
            <atom:updated>2020-06-22T23:28:06.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*fygqfizATFjt6ALek2W1jg.png" /></figure><p>If you’ve recently <a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">gotten started using the Sequelize command line interface (CLI)</a> to work with Sequelize, you’ve probably noticed that there’s not much you can do with your database if you don’t have any data.</p><p>Fortunately, an npm package called <a href="https://www.npmjs.com/package/faker"><strong>Faker</strong></a> can help fill that void. In this walkthrough, we’ll use the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> to create a simple project, then use Faker to generate reasonably convincing fake info for a group of fairly believable imaginary users.</p><p>Let’s start by installing Postgres, Sequelize, and the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> in a new project folder we’ll call sequelize-practice:</p><pre>mkdir sequelize-practice<br>cd sequelize-practice<br>npm init -y<br>npm install sequelize pg<br>npm install --save-dev sequelize-cli</pre><p>Next, let’s initialize a Sequelize project, then open the directory in our code editor:</p><pre>npx sequelize-cli init<br>code .</pre><blockquote>To learn more about any of the Sequelize CLI commands below, see:<br><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6"><strong>Getting Started with Sequelize CLI</strong></a></blockquote><p>Let’s configure our Sequelize project to work with Postgres. Find config.json in the /config directory and replace what’s there with this code:</p><pre>{<br>  &quot;development&quot;: {<br>    &quot;database&quot;: &quot;sequelize_practice_development&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;test&quot;: {<br>    &quot;database&quot;: &quot;sequelize_practice_test&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  },<br>  &quot;production&quot;: {<br>    &quot;database&quot;: &quot;sequelize_practice_production&quot;,<br>    &quot;host&quot;: &quot;127.0.0.1&quot;,<br>    &quot;dialect&quot;: &quot;postgres&quot;<br>  }<br>}</pre><p>Cool, now we can tell Sequelize to create the database:</p><pre>npx sequelize-cli db:create</pre><p>Next we will create a User model from the command line:</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,userName:string,password:string,jobTitle:string</pre><p>Running model:generate automatically creates both a model file and a migration with the attributes we’ve specified. For now, you won’t need to worry about (or edit) these in order to use Faker to generate seed data.</p><p>Now we’ll execute our migration to create the Users table in our database:</p><pre>npx sequelize-cli db:migrate</pre><h3>Seeding with Faker</h3><p>Now that our Sequelize project is set up, the fun can begin! We can ask Faker to create real-<em>seeming</em> information of all sorts, from generic <em>lorem ipsum</em> to imaginary email addresses and phone numbers.</p><p>Not only is this amusing — it also enables developers to test how their models, associations, and queries will behave once genuine data is entered.</p><p>Let’s install Faker:</p><pre>npm install faker</pre><p>Now we’ll tell the Sequelize CLI to generate a seed file:</p><pre>npx sequelize-cli seed:generate --name users</pre><p>This will generate a file in the /seeders subdirectory with a filename similar to 20190904165805-users.js. (The digits will be based on the current date and time.)</p><p>Replace the boilerplate code in that file with the code below:</p><pre>const faker = require(&#39;faker&#39;);</pre><pre>const users = [...Array(100)].map((user) =&gt; (<br>  {<br>    firstName: faker.name.firstName(),<br>    lastName: faker.name.lastName(),<br>    email: faker.internet.email(),<br>    userName: faker.internet.userName(),<br>    password: faker.internet.password(8),<br>    jobTitle: faker.name.jobTitle(),<br>    createdAt: new Date(),<br>    updatedAt: new Date()<br>  }<br>))</pre><pre>module.exports = {<br>  up: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkInsert(&#39;Users&#39;, users, {});<br>  },</pre><pre>  down: (queryInterface, Sequelize) =&gt; {<br>    return queryInterface.bulkDelete(&#39;Users&#39;, null, {});<br>  }<br>};</pre><p>Here we’re generating an array of 100 objects — and for each object, Faker will fill in the details using methods like faker.name.lastName() and faker.internet.email(). Then we just perform a bulk insert to add these entries to the database. Simple as that!</p><p>Once you’ve saved the file, execute it:</p><pre>npx sequelize-cli db:seed:all</pre><p>Drop into psql and query the database to find out what Faker cooked up:</p><pre>psql sequelize_practice_development<br>SELECT * FROM &quot;Users&quot;;</pre><blockquote>Seeding mistake? You can always undo: <em>npx sequelize-cli db:seed:undo</em></blockquote><p>Now you have a Sequelize project and a database with 100 fake users! Who did you end up with? Monique McTavish? Norm Sipowicz? Hansel Ramirez? Jane Doe? Jean-Luc Cho? It doesn’t matter! What’s important is that now you have data you can use to <a href="https://levelup.gitconnected.com/using-the-sequelize-cli-and-querying-4ba8d0ac4314">try out your Sequelize queries</a> as your project takes shape.</p><p><a href="http://marak.github.io/faker.js/#toc9__anchor">Faker’s list of available fake data</a> can help you customize seed data to fit your project’s needs. Try seeding two or more different tables after <a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233"><strong>creating a Sequelize association</strong></a>!</p><blockquote>This article was co-authored with <a href="https://www.linkedin.com/in/jeremy-r-rose">Jeremy Rose</a>, a software engineer, editor, and writer based in New York City.</blockquote><h3>More info on Sequelize CLI:</h3><ul><li><a href="https://medium.com/@brunopgalvao/getting-started-with-sequelize-cli-c33c797f05c6">Getting Started with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/using-the-sequelize-cli-and-querying-4ba8d0ac4314">Using Sequelize CLI and Querying</a></li><li><a href="https://medium.com/@brunopgalvao/creating-sequelize-associations-with-the-sequelize-cli-tool-d83caa902233">Creating Sequelize Associations with Sequelize CLI</a></li><li><a href="https://medium.com/@brunopgalvao/sequelize-cli-and-express-fb3ddefb9786">Sequelize CLI and Express</a></li><li><a href="https://medium.com/@brunopgalvao/build-an-express-api-with-sequelize-cli-and-express-router-963b6e274561">Build an Express API with Sequelize CLI and Express Router</a></li><li><a href="https://medium.com/@brunopgalvao/building-an-express-api-with-sequelize-cli-and-unit-testing-882c6875ed59">Building an Express API with Sequelize CLI and Unit Testing!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=824b3f4c4cfe" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/getting-started-with-sequelize-cli-using-faker-824b3f4c4cfe">Getting Started with Sequelize CLI using Faker</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>