<?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 misostack on Medium]]></title>
        <description><![CDATA[Stories by misostack on Medium]]></description>
        <link>https://medium.com/@gmmiso88?source=rss-80f696e2f101------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_07_2eyFaWKbZ7Vi</url>
            <title>Stories by misostack on Medium</title>
            <link>https://medium.com/@gmmiso88?source=rss-80f696e2f101------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:49:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gmmiso88/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[NextJS course Lesson 03 — Advanced Routing]]></title>
            <link>https://medium.com/@gmmiso88/nextjs-course-lesson-03-advanced-routing-bc63f95f1b78?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc63f95f1b78</guid>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjsvietnam]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[khoa-hoc-nextjs]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Mon, 27 May 2024 04:08:48 GMT</pubDate>
            <atom:updated>2024-05-27T04:08:48.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>NextJS course Lesson 03 — Advanced Routing</h3><p><strong>Note</strong> : The entire source code of this course is publicly available on github at <a href="https://github.com/nextjsvietnam/nextjs-tutorial-2024/tree/tutorial/lession-03">Nextjs Tutorial 2024</a></p><p>Main contents in this lesson:</p><ol><li>Authorization and redirection</li><li>Create shared layouts</li><li>Loading Screen</li><li>I18n — multilingual</li></ol><p>With the above content, we will continue with decentralization and navigation, as well as practice dividing shared layouts, displaying loading screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mgCml_vO7e1jKDyG" /></figure><p>Request:</p><ol><li>For pages in the Private group, only logged in customers can access them. In case users intentionally enter using fixed addresses, redirect users to the login page.</li><li>For logged in users, when re-visiting login-related pages such as: login, register, forget password, reset password, redirect them to the my-account page.</li><li>Pages in the customer’s Private group have a common interface, only the content differs.</li><li>Pages belonging to the login group also have a common interface, only the content differs.</li><li>All pages on the website use the same header and footer, different from the main content.</li></ol><h3>Authorization and redirection</h3><p>In this article, we will simulate that after the customer logs in, the information will be saved on cookies.</p><p>Therefore we will implement the logic as follows:</p><ul><li>If the user accesses pages belonging to the private group =&gt; check if this cookie exists or not, if so allow the user to access, otherwise redirect the user to the login page</li></ul><p>In NextJS we can do the following:</p><ol><li>Redirect users within the page using <strong>redirect</strong> function</li></ol><p>First, I will create additional pages one by one as follows: login, register, forgot-password, reset-password.</p><p>To group these pages in a group in a folder, nextjs supports us in creating folders with the syntax (folderName). When using this syntax, the created folder will not be included in the directory tree when nextjs route performs mapping between segments. and directory structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rn_86DLgI7Q8K-lY" /></figure><pre>// shared/auth.ts<br>import { AppCookie, AppRoute } from &quot;@/shared/constant&quot;;<br>import { cookies } from &quot;next/headers&quot;;<br>import { redirect } from &quot;next/navigation&quot;;<br>export const runUserGuard = () =&gt; {<br>  const cookieStore = cookies();<br>  if (!cookieStore.has(AppCookie.UserToken)) {<br>    return false;<br>  }<br>  try {<br>    const userCookie = cookieStore.get(AppCookie.UserToken);<br>    if (userCookie) {<br>      const user = JSON.parse(userCookie.value);<br>      return true;<br>    }<br>  } catch (error) {}<br>  return redirect(AppRoute.Login);<br>};</pre><pre>// my-account/page.tsx<br>import { runUserGuard } from &quot;@/shared/auth&quot;;<br>export default function MyAccount() {<br>  // run user Guard<br>  runUserGuard();<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;My Account&lt;/h1&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Please apply to the remaining pages. …</p><h3>Create shared layouts</h3><p>But what if I have more than 10 such pages, is there any other way?</p><ol><li>Group pages under my account into one group using the same layout</li></ol><pre>my-account<br>    page.tsx<br>    layout.tsx<br>    orders<br>        page.tsx<br>        [id]<br>            page.tsx</pre><p>Therefore, we need to readjust our path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*PMLGt9Qo_sVduvDV" /></figure><p>But if there is more than 1 such group, do we have any way?</p><ol><li>Use middleware</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GsT0lqX1KCsXlEo4" /></figure><pre>import AuthService from &quot;@/service/auth.service&quot;;<br>import { AppCookie, AppRoute } from &quot;@/shared/constant&quot;;<br>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br>export const authMiddleware = (req: NextRequest) =&gt; {<br>  // middleware/auth.ts<br>  const token = req.cookies.get(AppCookie.UserToken);<br>  const authService = new AuthService();<br>  const userToken = token?.name ? authService.verifyToken(token?.value) : null;<br>  // Assuming you have some function to verify the token<br>  if (!token || !userToken) {<br>    return NextResponse.redirect(new URL(AppRoute.Login, req.url));<br>  }<br>  return NextResponse.next();<br>};</pre><pre>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br>import { authMiddleware } from &quot;./app/middlewares/auth.middleware&quot;;<br>import { ProtectedRoutes } from &quot;./shared/constant&quot;;<br>// This function can be marked `async` if using `await` inside<br>export function middleware(req: NextRequest) {<br>  console.log(&quot;[Middleware Demo] : &quot; + req.url);<br>  const path = req.nextUrl.pathname;<br>  if (ProtectedRoutes.some((route) =&gt; path.startsWith(route))) {<br>    // apply auth middleware<br>    const redirectResponse = authMiddleware(req);<br>    if (redirectResponse) {<br>      return redirectResponse;<br>    }<br>  }<br>  return NextResponse.next();<br>}<br>// See &quot;Matching Paths&quot; below to learn more<br>export const config = {<br>  matcher: [<br>    /*<br>     * Match all request paths except for the ones starting with:<br>     * - _next/static (static files)<br>     * - _next/image (image optimization files)<br>     * - favicon.ico (favicon file)<br>     */<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      missing: [<br>        { type: &quot;header&quot;, key: &quot;next-router-prefetch&quot; },<br>        { type: &quot;header&quot;, key: &quot;purpose&quot;, value: &quot;prefetch&quot; },<br>      ],<br>    },<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      has: [<br>        { type: &quot;header&quot;, key: &quot;next-router-prefetch&quot; },<br>        { type: &quot;header&quot;, key: &quot;purpose&quot;, value: &quot;prefetch&quot; },<br>      ],<br>    },<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      has: [{ type: &quot;header&quot;, key: &quot;x-present&quot; }],<br>      missing: [{ type: &quot;header&quot;, key: &quot;x-missing&quot;, value: &quot;prefetch&quot; }],<br>    },<br>  ],<br>};</pre><pre>export const ProtectedRoutes = [&quot;/my-account&quot;];</pre><p>Now we will assume that if the user accesses the home page, it is considered a successful login. To test this auth middleware.</p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br>import { authMiddleware } from &quot;./app/middlewares/auth.middleware&quot;;<br>import { AppCookie, ProtectedRoutes } from &quot;./shared/constant&quot;;<br>import _db from &quot;../_db&quot;;<br>// This function can be marked `async` if using `await` inside<br>export function middleware(req: NextRequest) {<br>  console.log(&quot;[Middleware Demo] : &quot; + req.url);<br>const path = req.nextUrl.pathname;<br>// fake login<br>  if (path == &quot;/&quot;) {<br>    const response = NextResponse.next();<br>    response.cookies.set(AppCookie.UserToken, _db.tokens[0].token);<br>    return response;<br>  }<br>// ...<br>return NextResponse.next();<br>}<br>// ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5fDmlSUZ0ixUj6r6" /></figure><h3>Loading Screen</h3><p>In a website, there are too many blocks that do not need to be displayed immediately. As in the example below, the information that customers need to see immediately when they visit will usually be header, main content (top products). The random products section can be displayed later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HxUe6TiYxgqye-Ok" /></figure><p>With a normal website we will use AJAX to lazy load this section. Right in NextJS, just with simple syntax, we immediately have the above result.</p><p>Below is the mechanism of nextjs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WdmjH5NTxT7th46k" /></figure><ol><li>First, when the client requests to the server, the server will generate html from the page component</li><li>If the page has components wrapped in the Suspend tag, they will be converted to load later with javascript</li><li>When the website is downloaded, the html resource will be downloaded first, while the javascript will be loaded at the same time (there will be code that controls the loading of components that need to be streamed). When these scripts are executed, the data streaming process takes place, before that nextjs will automatically create placeholders with the content you defined in the Loading Component. Once the data is ready, your entire component will appear on the interface.</li><li>While the stream is taking place, you can still fully interact with the website, this is the key point of this technology.</li></ol><p>Benefit:</p><ul><li>Fast page load times</li><li>Display content in a user-friendly manner</li></ul><p>Let’s look at the code anyway</p><blockquote><em>src/components/SlowComponent.tsx</em></blockquote><pre>const wait = (timeout: number) =&gt; {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>      fetch(&quot;https://jsonplaceholder.typicode.com/todos/1&quot;)<br>        .then((res) =&gt; res.json())<br>        .then((data) =&gt; resolve(data));<br>    }, timeout);<br>  });<br>};<br>export const SlowComponent = async () =&gt; {<br>  const data: any = await wait(5000);<br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;{JSON.stringify(data)}&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><blockquote><em>src/app/page.tsx</em></blockquote><pre>import { SlowComponent } from &quot;@/components/SlowComponent&quot;;<br>import Link from &quot;next/link&quot;;<br>import { Suspense } from &quot;react&quot;;<br>import Loading from &quot;./loading&quot;;<br>export default function Home() {<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>      &lt;p&gt;Links to other pages with a tag&lt;/p&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/products&quot;&gt;Products&lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/products/mouse-pad-nextjsvietnam&quot;&gt;<br>            Mouse Pad NextJSVietNam<br>          &lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/cart&quot;&gt;Cart&lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/order&quot;&gt;Order&lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/my-account&quot;&gt;My Account&lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/my-account/orders&quot;&gt;My orders&lt;/a&gt;<br>        &lt;/li&gt;<br>        &lt;li&gt;<br>          &lt;a href=&quot;/my-account/orders/1&quot;&gt;My order detail&lt;/a&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>      &lt;p&gt;Links to other pages with Link tag&lt;/p&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;<br>          &lt;Link href=&quot;/products&quot;&gt;Products&lt;/Link&gt;<br>        &lt;/li&gt;<br>      &lt;/ul&gt;<br>      &lt;h2&gt;Slow Component&lt;/h2&gt;<br>      &lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>        &lt;SlowComponent&gt;&lt;/SlowComponent&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><h3>I18n — Multilingual</h3><p>Normally when working with React, to make multilingual websites we often use <a href="https://react.i18next.com/">https://react.i18next.com/</a> to make setup easy.</p><p>As for nextjs, how do we do it? It’s quite simple. Do you remember the rules about directory structure? Now we just need to create the corresponding folder structure</p><pre>[lang]<br>  page.tsx<br>  dictionaries.ts<br>  dictionaries<br>    en.json<br>    vi.json</pre><pre>{<br>  &quot;products&quot;: {<br>    &quot;cart&quot;: &quot;Add to Cart&quot;<br>  }<br>}</pre><pre>import &quot;server-only&quot;;<br>const dictionaries = {<br>  en: () =&gt; import(&quot;./dictionaries/en.json&quot;).then((module) =&gt; module.default),<br>  nl: () =&gt; import(&quot;./dictionaries/vi.json&quot;).then((module) =&gt; module.default),<br>};<br>export const getDictionary = async (locale) =&gt; dictionaries[locale]();</pre><pre>import { getDictionary } from &quot;./dictionaries&quot;;<br>export default async function Page({ params: { lang } }) {<br>  const dict = await getDictionary(lang); // en<br>  return &lt;button&gt;{dict.products.cart}&lt;/button&gt;; // Add to Cart<br>}</pre><p>But in reality using <a href="https://next-intl-docs.vercel.app/">next-intl</a> is still easier and has more benefits.</p><pre>npm install next-intl --save</pre><pre>import createNextIntlPlugin from &quot;next-intl/plugin&quot;;<br>const withNextIntl = createNextIntlPlugin();<br>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  async redirects() {<br>    return [<br>      // Basic redirect<br>      {<br>        // redirect to default language<br>        source: &quot;/&quot;,<br>        destination: &quot;/vi&quot;,<br>        permanent: true,<br>      },<br>    ];<br>  },<br>};<br>export default withNextIntl(nextConfig);</pre><p>The directory tree structure is as follows</p><pre>next.config.mjs<br>src<br>  app<br>    [locale]<br>      global.css<br>      layout.tsx<br>      loading.tsx<br>      page.tsx<br>  middleware.ts<br>  i18n.ts<br>  components<br>  layouts<br>    Footer.tsx<br>messages<br>  en.json<br>  vi.json</pre><pre>{<br>  &quot;layout&quot;: {<br>    &quot;headerTitle&quot;: &quot;NextJS Tutorial 2024&quot;<br>  }<br>}</pre><p>First, you need to move the following files to the new folder [locale]:</p><ul><li>global.css</li><li>layout.tsx</li><li>loading.tsx</li><li>page.tsx</li></ul><pre>// layout.tsx<br>import type { Metadata } from &quot;next&quot;;<br>import &quot;./globals.css&quot;;<br>import { NextIntlClientProvider } from &quot;next-intl&quot;;<br>import { getMessages } from &quot;next-intl/server&quot;;<br>export const metadata: Metadata = {<br>  title: &quot;NextJS Tutorial 2024&quot;,<br>  description: &quot;NextJS courses&quot;,<br>};<br>export default async function RootLayout({<br>  children,<br>  params: { locale },<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>  params: { locale: string };<br>}&gt;) {<br>  const messages = await getMessages({<br>    locale: locale,<br>  });<br>  return (<br>    &lt;html lang={locale}&gt;<br>      &lt;body&gt;<br>        &lt;NextIntlClientProvider messages={messages}&gt;<br>          {children}<br>        &lt;/NextIntlClientProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Create file i18n.ts</p><pre>import { notFound } from &quot;next/navigation&quot;;<br>import { getRequestConfig } from &quot;next-intl/server&quot;;<br>// Can be imported from a shared config<br>const locales = [&quot;en&quot;, &quot;vi&quot;];<br>export default getRequestConfig(async ({ locale }) =&gt; {<br>  // Validate that the incoming `locale` parameter is valid<br>  if (!locales.includes(locale as any)) notFound();<br>  return {<br>    messages: (await import(`../messages/${locale}.json`)).default,<br>  };<br>});</pre><p>Update middleware</p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import type { NextRequest } from &quot;next/server&quot;;<br>import { authMiddleware } from &quot;./app/middlewares/auth.middleware&quot;;<br>import { AppCookie, ProtectedRoutes } from &quot;./shared/constant&quot;;<br>import _db from &quot;../_db&quot;;<br>import createIntlMiddleware from &quot;next-intl/middleware&quot;;<br>import { redirect } from &quot;next/dist/server/api-utils&quot;;<br>// This function can be marked `async` if using `await` inside<br>export default async function middleware(req: NextRequest) {<br>  const [, locale, ...segments] = req.nextUrl.pathname.split(&quot;/&quot;);<br>  const path = req.nextUrl.pathname;<br>  // other middlewares<br>  if (locale != null) {<br>    console.log(&quot;[Middleware Demo] : &quot; + req.url);<br>   if (ProtectedRoutes.some((route) =&gt; path.startsWith(route))) {<br>      // apply auth middleware<br>      const redirectResponse = authMiddleware(req);<br>      if (redirectResponse) {<br>        return redirectResponse;<br>      }<br>    }<br>  }<br>  // next-intl middleware<br>  const handleI18nRouting = createIntlMiddleware({<br>    locales: [&quot;en&quot;, &quot;vi&quot;],<br>    defaultLocale: &quot;en&quot;,<br>    localePrefix: &quot;always&quot;,<br>  });<br>  const response = handleI18nRouting(req);<br>  // fake login<br>  if (path == `/${locale}`) {<br>    response.cookies.set(AppCookie.UserToken, _db.tokens[0].token);<br>  }<br>  return response;<br>}<br>// See &quot;Matching Paths&quot; below to learn more<br>export const config = {<br>  matcher: [<br>    // Paths for internationalization<br>    // &quot;/&quot;,<br>    &quot;/(en|vi)/:path*&quot;,<br>    /*<br>     * Match all request paths except for the ones starting with:<br>     * - _next/static (static files)<br>     * - _next/image (image optimization files)<br>     * - favicon.ico (favicon file)<br>     */<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      missing: [<br>        { type: &quot;header&quot;, key: &quot;next-router-prefetch&quot; },<br>        { type: &quot;header&quot;, key: &quot;purpose&quot;, value: &quot;prefetch&quot; },<br>      ],<br>    },<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      has: [<br>        { type: &quot;header&quot;, key: &quot;next-router-prefetch&quot; },<br>        { type: &quot;header&quot;, key: &quot;purpose&quot;, value: &quot;prefetch&quot; },<br>      ],<br>    },<br>    {<br>      source: &quot;/((?!_next/static|_next/image|favicon.ico).*)&quot;,<br>      has: [{ type: &quot;header&quot;, key: &quot;x-present&quot; }],<br>      missing: [{ type: &quot;header&quot;, key: &quot;x-missing&quot;, value: &quot;prefetch&quot; }],<br>    },<br>  ],<br>};</pre><p>Try to use</p><pre>// src/app/[locale]/page.tsx<br>import { SlowComponent } from &quot;@/components/SlowComponent&quot;;<br>import Link from &quot;next/link&quot;;<br>import { Suspense } from &quot;react&quot;;<br>import Loading from &quot;./loading&quot;;<br>import { useTranslations } from &quot;next-intl&quot;;<br>import { Footer } from &quot;@/layouts/Footer&quot;;<br>export default function Home() {<br>  const t = useTranslations(&quot;layout&quot;);<br>  return (<br>    &lt;&gt;<br>      &lt;header className=&quot;container-xl mx-auto p-4&quot;&gt;<br>        &lt;h1&gt;{t(&quot;headerTitle&quot;)}&lt;/h1&gt;<br>      &lt;/header&gt;<br>      &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>        &lt;h1&gt;Home Page&lt;/h1&gt;<br>        &lt;p&gt;Links to other pages with a tag&lt;/p&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/products&quot;&gt;Products&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/products/mouse-pad-nextjsvietnam&quot;&gt;<br>              Mouse Pad NextJSVietNam<br>            &lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/cart&quot;&gt;Cart&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/order&quot;&gt;Order&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/my-account&quot;&gt;My Account&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/my-account/orders&quot;&gt;My orders&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;a href=&quot;/my-account/orders/1&quot;&gt;My order detail&lt;/a&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;p&gt;Links to other pages with Link tag&lt;/p&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;<br>            &lt;Link href=&quot;/products&quot;&gt;Products&lt;/Link&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;h2&gt;Slow Component&lt;/h2&gt;<br>        &lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>          &lt;SlowComponent&gt;&lt;/SlowComponent&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/main&gt;<br>      &lt;Footer&gt;&lt;/Footer&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Switch language</p><pre>// layouts/Footer<br>&quot;use client&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>export const Footer = () =&gt; {<br>  const router = useRouter();<br>  const switchLanguage = (language: string) =&gt; {<br>    router.push(language);<br>  };<br>  return (<br>    &lt;footer&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={() =&gt; switchLanguage(&quot;en&quot;)}&gt;English&lt;/button&gt;<br>        &lt;button onClick={() =&gt; switchLanguage(&quot;vi&quot;)}&gt;Vietnamese&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/footer&gt;<br>  );<br>};</pre><p>Feel free to access full article at K<a href="https://nextjsvietnam.com/post/khoa-hoc-nextjs-bai-03-advanced-routing/">hoá học NextJS Bài 03 — Advanced Routing</a></p><p><a href="https://nextjsvietnam.com/">#nextjsvietnam</a> <a href="https://nextjsvietnam.com/categories/nextjs-tutorial/">#nextjs-tutorial</a> <a href="https://nextjsvietnam.com/categories/nextjs-tutorial/">#khoa-hoc-nextjs</a></p><p>Code with fun and joy!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc63f95f1b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NextJS 2024 course — Lesson 02: NextJS project structure]]></title>
            <link>https://medium.com/@gmmiso88/nextjs-2024-course-lesson-02-nextjs-project-structure-c5734aa88b2e?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5734aa88b2e</guid>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs14]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Sun, 19 May 2024 07:31:52 GMT</pubDate>
            <atom:updated>2024-05-19T07:32:44.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>NextJS 2024 course — Lesson 02: NextJS project structure</h3><p><strong>Note</strong> : The entire source code of this course is publicly available on github at <a href="https://github.com/nextjsvietnam/nextjs-tutorial-2024/tree/tutorial/lession-02">Nextjs Tutorial 2024</a></p><p>Main contents in this lesson:</p><ol><li>Initialize the NextJS project</li><li>Compare the structure of a website with the structure of a NextJS project</li><li>Create the most basic directory structure for a NextJS project</li><li>Install and configure VSCode for NextJS project</li><li>Deploy your first project to the server</li></ol><h3>Initialize the NextJS project</h3><p>There are 2 ways to create a NextJS project</p><ul><li>Method 1: Automatic Installation</li><li>Method 2: Manual Installation</li></ul><p>Normally we will choose method 1 to save time, method 2 is for those with more in-depth knowledge, and is often used when needing to convert a SPA project written in ReactJS to Server Side Render using NextJS. .</p><h3>Method 1: Automatic Installation</h3><pre>npx create-next-app@latest [your-project-name]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xWaSa8bGEDHxQi4F" /></figure><p>After installation is complete, we will go through the most basic structure of NextJS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hXung31bU5PvRhJs" /></figure><p>Let’s run the project with the commands available in package.json</p><pre>&quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;build&quot;: &quot;next build&quot;,<br>    &quot;start&quot;: &quot;next start&quot;,<br>    &quot;lint&quot;: &quot;next lint&quot;<br>  },</pre><pre>npm run dev</pre><p>Interface for the first time after running the above command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cC-sw4Zddxe6toki" /></figure><p>So you’ve gone 1/4 of the way through this lesson. There will be many questions like, so with such an initial directory structure, how do we declare the new page, how does the reactjs code work, and where will other resources such as images and css be placed? , how to call the api to get data and display it on the website,…</p><p>For ease of access, we start from the structure of a traditional website with the following directory tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZuXPkIVoR7Q-Po31" /></figure><p>Let’s analyze the structure of the simple sales website above as follows.</p><p>We will have the following pages one after another:</p><ol><li>Home: The home page displays the latest, hot, and promotional products</li><li>Products: displays all the shop’s products, supports search and classification according to a number of criteria: price, product category, product code. Supports sorting by price, number of purchases,…</li><li>Product Detail: displays product details including: images, prices, product information, purchase buttons, …</li><li>Cart: shopping cart, displays products in the customer’s cart</li><li>Order: page to confirm customer’s order information</li><li>My Account: customer’s personal information page, supports updating delivery information and order information</li><li>My Orders: displays a list of placed orders</li><li>Order Details: displays detailed information of an order.</li></ol><p>Quite a lot, isn’t it? So to build a website like the above, we will have the following requirements when structuring a project:</p><ol><li>Global styles: general colors, sizes, fonts of the entire website,</li><li>Assets: images, css, javascript, …</li><li>Shared Components: common components for websites from small to large. For example: header, footer, form elements, buttons, …</li><li>Route: corresponding path to the pages</li><li>Fetching Data: retrieve data from the server</li><li>Rendering: the part that creates the html content of each page based on data</li><li>Authentication: login part, to block unauthorized users from accessing content that is not theirs, such as my account, my orders,…</li></ol><p>In nextjs, there is no specific syntax to help us declare routes and corresponding pages. Nextjs itself will provide a self-deduced route according to the tree structure as follows:</p><p>This is the original image on the homepage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oaG_IvelEGRmFPyx" /></figure><p>And this is the structure of our website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JXF8vCOltbfo49wE" /></figure><p>URL structure of a website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UTOGiHezUbu2YLqv" /></figure><p>So what structure does nextjs automatically deduce? It will basically be based on the structure of a website’s URL and the corresponding directory structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HSPY7bG2BSlA26hv" /></figure><blockquote><em>[slug] is exactly the directory</em></blockquote><p>Combined with nextjs naming convention below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rjG__THMejCkJ7jE" /></figure><p>Let’s build the project’s directory structure as follows:</p><blockquote><em>src/app/global.css : file containing our global css, in this example we use tailwind</em></blockquote><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><blockquote><em>layout.tsx: this is the component used as a common layout for child components</em></blockquote><pre>import type { Metadata } from &quot;next&quot;;<br>import &quot;./globals.css&quot;;<br><br>export const metadata: Metadata = {<br>  title: &quot;NextJS Tutorial 2024&quot;,<br>  description: &quot;NextJS courses&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><blockquote><em>page.tsx: This is the file that will correspond to the route segment</em></blockquote><pre>export default function Home() {<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>According to predetermined rules, we create routes for the following pages in turn:</p><p>For simplicity all the paths below default to the src/app directory</p><ol><li>Home : page.tsx</li><li>Products: products/page.tsx</li><li>Product Details: products/[slug].tsx</li><li>Cart: cart/page.tsx</li><li>Order: order/page.tsx</li><li>My Account: my-account/page.tsx</li><li>My Orders: my-orders/page.tsx</li><li>My Order Details: my-orders/[id]/page.tsx</li></ol><p>Please stop and practice.</p><pre>mkdir -p products products/[slug] cart order my-account my-orders my-orders/[id]</pre><p>So after creating the folder and file structure, how to write code to display the website. Simply export a default component in the corresponding file. Note that you should name the component according to the page for easy management.</p><pre>export default function Products() {<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;Products&lt;/h1&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Let’s create links to the pages you have created. We have 2 ways to use the a tag or Link Component of NextJS.</p><pre>import Link from &quot;next/link&quot;;<br><br>export default function Products() {<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;Products&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {[1, 2, 3, 4, 5, 6].map((i) =&gt; (<br>          &lt;&gt;<br>            &lt;li&gt;<br>              &lt;Link href={`/products/${i}`}&gt;Product {i}&lt;/Link&gt;<br>            &lt;/li&gt;<br>          &lt;/&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><h4>Let’s compare the differences between the two methods</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwopG9mM0Qe8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwopG9mM0Qe8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwopG9mM0Qe8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6fada90a2381a5752e261988f081b1e/href">https://medium.com/media/c6fada90a2381a5752e261988f081b1e/href</a></iframe><p>It seems pretty good, but how to handle [slug] and [id].</p><blockquote><em>Dynamic Segments are passed as the params prop to layout, page, route, and generateMetadata function</em></blockquote><p>Oh, so segments of this form will be passed into the component’s params prop: layout, page, route, generateMetadata function.</p><p>Let’s try</p><pre>import Link from &quot;next/link&quot;;<br><br>type ProductDetailProps = {<br>  params: {<br>    slug: string;<br>  };<br>};<br>// let&#39;s fake a function to find product detail by slug/id<br>const PRODUCTS = [<br>  {<br>    id: 1,<br>    slug: &quot;mouse-pad-nextjsvietnam&quot;,<br>    name: &quot;Mouse Pad NextJSVietNam&quot;,<br>    price: 15,<br>    currency: &quot;USD&quot;,<br>    image:<br>      &quot;https://gist.github.com/assets/31009750/06f69548-c14b-47d0-b650-7af3a023b750&quot;,<br>  },<br>];<br><br>const findProductBySlugOrId = (value: string) =&gt; {<br>  // find by id first<br>  let product = null;<br>  try {<br>    const id: number = parseInt(value);<br>    product = PRODUCTS.find((p) =&gt; p.id == id);<br>    if (product) {<br>      return product;<br>    }<br>    // otherwise find by slug<br>    product = PRODUCTS.find((p) =&gt; p.slug === value.toLowerCase());<br>  } catch (error) {<br>    console.log(error);<br>  }<br>  return product;<br>};<br><br>export default function ProductDetail({ params }: ProductDetailProps) {<br>  const { slug } = params;<br>  const product = findProductBySlugOrId(slug);<br>  let content = &lt;&gt;&lt;/&gt;;<br>  if (!product) {<br>    content = (<br>      &lt;&gt;<br>        &lt;h1&gt;Product not found!&lt;/h1&gt;<br>        &lt;p&gt;<br>          Please go back to &lt;Link href=&quot;/products&quot;&gt;product list&lt;/Link&gt;<br>        &lt;/p&gt;<br>      &lt;/&gt;<br>    );<br>  } else {<br>    content = (<br>      &lt;&gt;<br>        &lt;h1&gt;Product Detail&lt;/h1&gt;<br>        &lt;p&gt;Name: {product.name}&lt;/p&gt;<br>        &lt;p&gt;<br>          Price: {product.price} {product.currency}<br>        &lt;/p&gt;<br>        &lt;p&gt;<br>          &lt;img src={product.image} alt={product.name} /&gt;<br>        &lt;/p&gt;<br>      &lt;/&gt;<br>    );<br>  }<br>  return &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;{content}&lt;/main&gt;;<br>}</pre><p>Try accessing the following 3 links:</p><ol><li><a href="http://localhost:3000/products/mouse-pad-nextjsvietnam">http://localhost:3000/products/mouse-pad-nextjsvietnam</a> =&gt; there are products displayed</li><li><a href="http://localhost:3000/products/1">http://localhost:3000/products/1</a> =&gt; has products displayed (same product as link 1)</li><li><a href="http://localhost:3000/products/5">http://localhost:3000/products/5</a> =&gt; product not found</li></ol><p>Please continue to apply with [id] of my order details</p><blockquote><em>URL : </em><a href="http://localhost:3000/my-orders/1"><em>http://localhost:3000/my-orders/1</em></a></blockquote><pre>type OrderProps = {<br>  params: {<br>    id: string;<br>  };<br>};<br>const PRODUCTS = [<br>  {<br>    id: 1,<br>    slug: &quot;mouse-pad-nextjsvietnam&quot;,<br>    name: &quot;Mouse Pad NextJSVietNam&quot;,<br>    price: 15,<br>    currency: &quot;USD&quot;,<br>    image:<br>      &quot;https://gist.github.com/assets/31009750/06f69548-c14b-47d0-b650-7af3a023b750&quot;,<br>  },<br>];<br>const ORDERS = [<br>  { id: 1, items: [{ id: 1, product: PRODUCTS[0], quality: 5 }] },<br>];<br>const findOrderById = (orderId: string) =&gt; {<br>  return ORDERS.find((order) =&gt; order.id === parseInt(orderId));<br>};<br>export default function MyOrderDetail({ params }: OrderProps) {<br>  const { id } = params;<br>  const order = findOrderById(id);<br>  return (<br>    &lt;main className=&quot;container-xl mx-auto p-4&quot;&gt;<br>      &lt;h1&gt;Order&lt;/h1&gt;<br>      &lt;table&gt;<br>        &lt;thead&gt;<br>          &lt;tr&gt;<br>            &lt;th&gt;Product Name&lt;/th&gt;<br>            &lt;th&gt;Product Image&lt;/th&gt;<br>            &lt;th&gt;Quality&lt;/th&gt;<br>            &lt;th&gt;Total&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          {order?.items.map((item) =&gt; (<br>            &lt;tr&gt;<br>              &lt;td&gt;{item.product.name}&lt;/td&gt;<br>              &lt;td&gt;<br>                &lt;img src={item.product.image} width={150} height={&quot;auto&quot;} /&gt;<br>              &lt;/td&gt;<br>              &lt;td&gt;{item.quality}&lt;/td&gt;<br>              &lt;td&gt;<br>                {item.quality * item.product.price} {item.product.currency}<br>              &lt;/td&gt;<br>            &lt;/tr&gt;<br>          ))}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Code fun.</p><p>Feel free to access full article at <a href="https://nextjsvietnam.com/post/khoa-hoc-nextjs-bai-02-cau-truc-du-an-nextjs/">NextJS Tutorial 2024</a>.</p><p><a href="https://nextjsvietnam.com/">#nextjsvietnam</a> <a href="https://nextjsvietnam.com/categories/nextjs-tutorial/">#nextjs-tutorial-2024</a> <a href="https://nextjsvietnam.com/categories/nextjs-tutorial/">#khoa-hoc-nextjs-2024</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5734aa88b2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nestjs Passing Data Between Layers in Domain Driven Design]]></title>
            <link>https://medium.com/@gmmiso88/nestjs-passing-data-between-layers-in-domain-driven-design-4899bcd7f872?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/4899bcd7f872</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 12:12:12 GMT</pubDate>
            <atom:updated>2024-04-27T12:12:12.492Z</atom:updated>
            <content:encoded><![CDATA[<p>We determined that we will have 3 layers: Presentation(Controller), Service, Data Layer(Repository). And the flow is:</p><ul><li>Controllers will inject Services to use</li><li>Services will inject Repository to use.</li></ul><p>So when passing data between layers, the dto/models will be use should belongs to which layers.</p><h3>Top-Down Approach (1st Option)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JhLu3dlgVV0BYViO" /></figure><h3>Controllers Layer:</h3><ul><li>Responsibility: Handle incoming HTTP requests, delegate business logic to services.</li><li>Data Transfer: Interact with DTOs provided by services for transferring data between the client and the server.</li><li>Dependency: Depend on services for handling business logic. Remain unaware of entities.</li></ul><h3>Services Layer:</h3><ul><li>Responsibility: Contain business logic, orchestrate data flow, and interact with repositories.</li><li>Data Transfer: Map DTOs to entities before passing them to the repository layer, and vice versa. Provide DTOs to controllers for data exchange.</li><li>Dependency: Depend on repositories for data access and storage operations.</li></ul><h3>Repositories Layer:</h3><ul><li>Responsibility: Handle data access and storage operations, interact directly with the database, and manage entities.</li><li>Data Transfer: Operate directly with entities without any knowledge of DTOs or higher-level business logic.</li><li>Dependency: Independent of higher-level layers, operates directly with the database.</li></ul><h3>User Module Sample</h3><blockquote><em>User Controller</em></blockquote><pre>import { Controller, Get, Post, Body } from &quot;@nestjs/common&quot;;<br>import { UserService } from &quot;./user.service&quot;;<br>import { CreateUserDTO, UserDTO } from &quot;./dto/user.dto&quot;;<br>@Controller(&quot;users&quot;)<br>export class UserController {<br>  constructor(private readonly userService: UserService) {}<br>  @Get()<br>  async getUsers(): Promise&lt;UserDTO[]&gt; {<br>    return this.userService.getUsers();<br>  }<br>  @Post()<br>  async createUser(@Body() createUserDTO: CreateUserDTO): Promise&lt;UserDTO&gt; {<br>    return this.userService.createUser(createUserDTO);<br>  }<br>}</pre><blockquote><em>User Service</em></blockquote><pre>import { Injectable, BadRequestException } from &quot;@nestjs/common&quot;;<br>import { UserRepository } from &quot;./user.repository&quot;;<br>import { UserEntity } from &quot;./user.entity&quot;;<br>import { CreateUserDTO, UserDTO } from &quot;./dto/user.dto&quot;;<br>import { validate } from &quot;class-validator&quot;;<br>@Injectable()<br>export class UserService {<br>  constructor(private readonly userRepository: UserRepository) {}<br>  async getUsers(): Promise&lt;UserDTO[]&gt; {<br>    const users: UserEntity[] = await this.userRepository.findAll();<br>    return users.map((user) =&gt; this.mapEntityToDTO(user));<br>  }<br>  async createUser(createUserDTO: CreateUserDTO): Promise&lt;UserDTO&gt; {<br>    // Perform data validation using class-validator<br>    const errors = await validate(createUserDTO);<br>    if (errors.length &gt; 0) {<br>      throw new BadRequestException(errors);<br>    }<br>    // Additional business logic for creating a user<br>    const userEntity: UserEntity = this.mapDTOToEntity(createUserDTO);<br>    const createdUser: UserEntity = await this.userRepository.create(<br>      userEntity<br>    );<br>    return this.mapEntityToDTO(createdUser);<br>  }<br>  // Additional methods and business logic can be added here<br>  private mapDTOToEntity(dto: CreateUserDTO): UserEntity {<br>    // Map DTO to entity<br>  }<br>  private mapEntityToDTO(entity: UserEntity): UserDTO {<br>    // Map entity to DTO<br>  }<br>}</pre><blockquote><em>User Repository</em></blockquote><pre>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { UserEntity } from &quot;./user.entity&quot;;<br>@Injectable()<br>export class UserRepository {<br>  async findAll(): Promise&lt;UserEntity[]&gt; {<br>    // Retrieve users from the database<br>  }<br>  async create(user: UserEntity): Promise&lt;UserEntity&gt; {<br>    // Save user to the database<br>  }<br>}</pre><h3>Pros:</h3><ol><li><strong>Clear Separation of Concerns</strong>: The top-down approach enforces a clear separation of concerns, with controllers handling HTTP request/response logic, services containing business logic, and repositories managing data access/storage operations.</li><li><strong>Modularity</strong>: Each layer has a specific responsibility, making it easier to understand and maintain the codebase. Changes in one layer typically have minimal impact on others.</li><li><strong>Scalability</strong>: The layered architecture facilitates scalability, as new features or changes can be implemented within specific layers without affecting the overall structure.</li><li><strong>Testability</strong>: The separation of concerns makes it easier to write unit tests for each layer independently, improving overall test coverage and code quality.</li><li><strong>Flexibility</strong>: By defining clear interfaces between layers, developers can easily swap out implementations or refactor code within a layer without affecting other parts of the application.</li></ol><h3>Cons:</h3><ol><li><strong>Increased Complexity</strong>: Managing the interactions between layers, especially in larger applications with complex business logic, can introduce complexity and make the code harder to maintain.</li><li><strong>Performance Overhead</strong>: Passing data between layers, especially when using DTOs or performing excessive data transformation, can incur performance overhead, impacting application performance.</li><li><strong>Potential for Duplication</strong>: In some cases, similar logic may be duplicated across layers, leading to code duplication and maintenance overhead.</li><li><strong>Dependency Management</strong>: Managing dependencies between layers, especially when dealing with circular dependencies or complex data flows, can be challenging and require careful design.</li><li><strong>Over-Abstraction</strong>: Overly strict layering or excessive abstraction can lead to over-engineering and make the codebase harder to understand for new developers.</li></ol><p>Overall, while the top-down approach provides clear benefits in terms of separation of concerns, modularity, and testability, it also comes with challenges related to complexity, performance, and dependency management. It’s essential to strike a balance and carefully design the interactions between layers to ensure a maintainable and scalable architecture.</p><h3>Bottom-Up Approach (2nd Option)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISMdAzqut6-eHv6L" /></figure><h3>Bottom-Up Approach Concepts:</h3><p><strong>Repositories Layer:</strong></p><ul><li><strong>Foundation Layer</strong>: The repository layer forms the foundation of the application. It is responsible for handling data access and storage operations, directly interacting with the database and managing entities.</li><li><strong>Interaction with Database</strong>: Repositories interact directly with the database, executing queries and managing transactions to retrieve, create, update, and delete data.</li><li><strong>Awareness of DTOs</strong>: Repositories may be aware of DTOs, utilizing them for data manipulation and storage operations.</li></ul><p><strong>Services Layer:</strong></p><ul><li><strong>Built upon Repositories</strong>: The service layer is built upon the foundation provided by the repository layer. It contains business logic and orchestrates data flow within the application.</li><li><strong>Mapping DTOs to Entities</strong>: Services may handle DTO-to-entity mapping, but they are not required to do so if repositories are aware of DTOs.</li><li><strong>Business Logic</strong>: Services encapsulate business logic, performing operations such as validation, transformation, and coordination of data between different parts of the application.</li></ul><p><strong>Controllers Layer:</strong></p><ul><li><strong>Dependency on Services</strong>: Controllers depend on the service layer for handling HTTP requests and delegating business logic.</li><li><strong>HTTP Request Handling</strong>: Controllers handle incoming HTTP requests, utilizing DTOs defined at the controller layer to transfer data between the client and the server.</li><li><strong>Delegation to Services</strong>: Controllers delegate the execution of business logic to services, maintaining a separation of concerns and promoting modularity.</li></ul><h3>User Module Sample</h3><pre>// UserEntity.ts<br>export class UserEntity {<br>  id: number;<br>  name: string;<br>  email: string;<br>  constructor(id: number, name: string, email: string) {<br>    this.id = id;<br>    this.name = name;<br>    this.email = email;<br>  }<br>}<br>// UserDTO.ts<br>export class UserDTO {<br>  name: string;<br>  email: string;<br>}<br>// UserRepository.ts<br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { UserEntity } from &quot;./UserEntity&quot;;<br>import { UserDTO } from &quot;./UserDTO&quot;;<br>@Injectable()<br>export class UserRepository {<br>  async createUser(userData: UserDTO): Promise&lt;UserEntity&gt; {<br>    // Save user data to the database and return the created user entity<br>    const createdUser = new UserEntity(1, userData.name, userData.email); // Simulated creation<br>    return createdUser;<br>  }<br>}<br>// UserService.ts<br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { UserRepository } from &quot;./UserRepository&quot;;<br>import { UserEntity } from &quot;./UserEntity&quot;;<br>import { UserDTO } from &quot;./UserDTO&quot;;<br>@Injectable()<br>export class UserService {<br>  constructor(private readonly userRepository: UserRepository) {}<br>  async createUser(userData: UserDTO): Promise&lt;UserEntity&gt; {<br>    // Additional business logic<br>    return this.userRepository.createUser(userData);<br>  }<br>}<br>// UserController.ts<br>import { Controller, Post, Body } from &quot;@nestjs/common&quot;;<br>import { UserService } from &quot;./UserService&quot;;<br>import { UserDTO } from &quot;./UserDTO&quot;;<br>import { UserEntity } from &quot;./UserEntity&quot;;<br>@Controller(&quot;users&quot;)<br>export class UserController {<br>  constructor(private readonly userService: UserService) {}<br>  @Post()<br>  async createUser(@Body() userData: UserDTO): Promise&lt;UserEntity&gt; {<br>    return this.userService.createUser(userData);<br>  }<br>}</pre><h3>Pros:</h3><ol><li><strong>Reduced Duplication</strong>: By allowing lower-level components (e.g., repositories) to be more aware and responsible, duplication of code and logic can be reduced. This can lead to cleaner and more maintainable code.</li><li><strong>Simplified Interactions</strong>: With lower-level components handling more responsibility, interactions between layers may become simpler and more streamlined. This can improve overall code readability and understandability.</li><li><strong>Flexibility in Mapping</strong>: Since repositories may be aware of DTOs, there is flexibility in how data is mapped between layers. This can provide more options for handling data transformation and manipulation.</li></ol><h3>Cons:</h3><ol><li><strong>Tighter Coupling</strong>: Allowing lower-level components to be more aware of higher-level concepts (e.g., DTOs) can lead to tighter coupling between layers. Changes in one layer may have a greater impact on other layers, potentially reducing modularity.</li><li><strong>Potential Complexity</strong>: With more responsibility distributed to lower-level components, the overall complexity of the system may increase. Managing interactions and dependencies between layers may become more challenging, especially in larger applications.</li><li><strong>Risk of Over-Engineering</strong>: Allowing repositories to be aware of DTOs and handle more responsibility may lead to over-engineering if not carefully managed. Developers may be tempted to introduce unnecessary complexity or functionality into lower-level components, leading to bloated code.</li><li><strong>Limited Flexibility in Mapping</strong>: While repositories may be aware of DTOs, this approach may limit flexibility in how data is mapped between layers. If DTOs change frequently or need to be transformed differently in different contexts, repositories may become less adaptable.</li></ol><h3>Hybrid Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vlqUo3M4QnnHgFlW" /></figure><h3>Controllers Layer</h3><h4>Responsibilities:</h4><ul><li>Handle incoming HTTP requests and respond to the client.</li><li>Utilize DTOs (Data Transfer Objects) to validate and structure incoming data from the client.</li></ul><h4>Key Features:</h4><ul><li><strong>Decorators and Routing</strong>: Use decorators to define routes, extract request data, and apply middleware, keeping the controllers clean and focused on their routing responsibilities.</li><li><strong>Error Handling</strong>: Implement exception filters to catch and handle errors from the business logic, ensuring responses are user-friendly.</li></ul><h3>Services Layer</h3><h4>Responsibilities:</h4><ul><li>Contain and manage the core business logic of the application.</li><li>Orchestrate data flow between the presentation and data layers, ensuring that business rules are adhered to and data integrity is maintained.</li></ul><h4>Key Features:</h4><ul><li><strong>Framework Agnosticism</strong>: Services should be designed to be as independent of the web framework as possible, which enhances testability and reusability.</li><li><strong>Dependency Injection</strong>: Utilize NestJS’s powerful dependency injection container to manage service dependencies, promoting loose coupling and modular architecture.</li></ul><h3>Repositories Layer</h3><h4>Responsibilities:</h4><ul><li>Handle data persistence and retrieval operations directly with the database.</li><li>Execute queries, manage transactions, and perform data transformations.</li></ul><h4>Key Features:</h4><ul><li><strong>Entity Management</strong>: Repositories typically work with entities rather than DTOs, ensuring that the data layer remains focused on data persistence and operations.</li><li><strong>Custom Repository Classes</strong>: For complex queries or database interactions, extend the basic repository functionality provided by the ORM to create custom repository classes.</li></ul><h3>Overall Design Considerations</h3><ul><li><strong>Modularity</strong>: Promote a modular approach where each module encapsulates a certain business domain, thus enhancing maintainability and scalability.</li><li><strong>Testing</strong>: Each layer can be independently tested. Controllers can be tested using end-to-end tests, services can be unit tested, and repositories can be tested using integration tests with the database.</li></ul><h3>Code samples</h3><pre>// src/user/entities/user.entity.ts<br>import { Entity, Column, PrimaryGeneratedColumn } from &quot;typeorm&quot;;<br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br>  @Column({ unique: true })<br>  username: string;<br>  @Column()<br>  password: string; // In a real-world application, you would hash this value before storage<br>  @Column()<br>  email: string;<br>  @Column({ default: true })<br>  isActive: boolean;<br>}</pre><pre>// src/user/repositories/user.repository.ts<br>import { EntityRepository, Repository } from &quot;typeorm&quot;;<br>import { User } from &quot;../entities/user.entity&quot;;<br>@EntityRepository(User)<br>export class UserRepository extends Repository&lt;User&gt; {<br>  // Additional queries and methods specific to the user data can be placed here<br>}</pre><pre>// src/user/services/user.service.ts<br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { InjectRepository } from &quot;@nestjs/typeorm&quot;;<br>import { UserRepository } from &quot;../repositories/user.repository&quot;;<br>import { User } from &quot;../entities/user.entity&quot;;<br>@Injectable()<br>export class UserService {<br>  constructor(<br>    @InjectRepository(UserRepository)<br>    private userRepository: UserRepository<br>  ) {}<br>async findAll(): Promise&lt;User[]&gt; {<br>    return this.userRepository.find();<br>  }<br>  async findOne(id: number): Promise&lt;User | undefined&gt; {<br>    return this.userRepository.findOne(id);<br>  }<br>  async findByUsername(username: string): Promise&lt;User | undefined&gt; {<br>    return this.userRepository.findOne({ where: { username } });<br>  }<br>  async create(userData: User): Promise&lt;User&gt; {<br>    return this.userRepository.save(userData);<br>  }<br>  async update(id: number, userData: Partial&lt;User&gt;): Promise&lt;User&gt; {<br>    await this.userRepository.update(id, userData);<br>    return this.userRepository.findOne(id);<br>  }<br>  async remove(id: number): Promise&lt;void&gt; {<br>    await this.userRepository.delete(id);<br>  }<br>}</pre><pre>// src/user/controllers/user.controller.ts<br>import {<br>  Controller,<br>  Get,<br>  Post,<br>  Body,<br>  Param,<br>  Delete,<br>  Put,<br>} from &quot;@nestjs/common&quot;;<br>import { UserService } from &quot;../services/user.service&quot;;<br>import { User } from &quot;../entities/user.entity&quot;;<br>@Controller(&quot;users&quot;)<br>export class UserController {<br>  constructor(private readonly userService: UserService) {}<br>  @Get()<br>  async findAll(): Promise&lt;User[]&gt; {<br>    return this.userService.findAll();<br>  }<br>  @Get(&quot;:id&quot;)<br>  async findOne(@Param(&quot;id&quot;) id: number): Promise&lt;User&gt; {<br>    return this.userService.findOne(id);<br>  }<br>  @Post()<br>  async create(@Body() userData: User): Promise&lt;User&gt; {<br>    return this.userService.create(userData);<br>  }<br>  @Put(&quot;:id&quot;)<br>  async update(<br>    @Param(&quot;id&quot;) id: number,<br>    @Body() userData: Partial&lt;User&gt;<br>  ): Promise&lt;User&gt; {<br>    return this.userService.update(id, userData);<br>  }<br>  @Delete(&quot;:id&quot;)<br>  async remove(@Param(&quot;id&quot;) id: number): Promise&lt;void&gt; {<br>    return this.userService.remove(id);<br>  }<br>}</pre><h3>Pros</h3><ol><li><strong>Separation of Concerns: </strong>Ensures each layer focuses on specific responsibilities, simplifying maintenance and extension of the application.</li><li><strong>Scalability: </strong>Individual layers can scale based on specific needs, aiding efficient resource utilization.</li><li><strong>Reusability: </strong>Business logic in the services layer can be reused across different parts of the application, enhancing code efficiency.</li><li><strong>Testability: </strong>Independent testing of layers streamlines test case writing and debugging.</li><li><strong>Modularity: </strong>Enhances application organization through modular encapsulation of components, aligned with NestJS’s architecture.</li><li><strong>Flexibility in Data Management: </strong>The repository layer’s focus on data handling allows easy modifications to persistence logic without impacting other layers.</li></ol><h3>Cons</h3><ol><li><strong>Complexity in Setup : </strong>Initial setup can be complex and might be daunting for new developers.</li><li><strong>Overhead: </strong>Additional code and abstraction layers can lead to unnecessary complexity in smaller projects.</li><li><strong>Dependency Management: </strong>Managing dependencies across multiple layers can be challenging, especially in large projects.</li><li><strong>Potential for Redundant Abstractions: </strong>Data may need to be mapped and transformed across layers multiple times, potentially reducing performance.</li><li><strong>Learning Curve: </strong>NestJS’s advanced features such as Dependency Injection, Modules, and Decorators can have a steep learning curve.</li><li><strong>Database-Driven Design Constraints: </strong>Tight coupling of entities to the database schema can sometimes limit the implementation flexibility for certain business logic.</li></ol><p>This structured approach is ideal for medium to large-scale applications but may be excessive for smaller projects. It is crucial to assess the project’s specific needs to determine the most suitable architecture.</p><h3>Conclusion</h3><ul><li>Feel free to design your approach to adapt with your business requirements and your teams.</li></ul><p>Code fun ^^.</p><p>Read full article about this topic at <a href="https://nextjsvietnam.com/post/nestjs-passing-data-between-layers-in-ddd/">Nestjs Passing Data Between Layers in Domain Driven Design</a>.</p><p><a href="https://nextjsvietnam.com/">#nextjsvietnam</a> <a href="https://nextjsvietnam.com/categories/nestjs/">#nestjs-tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4899bcd7f872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Php Tutorial 2024] Lession 01 — Setup Php Development Environment in Windows 10]]></title>
            <link>https://medium.com/@gmmiso88/php-tutorial-2024-lession-01-setup-php-development-environment-in-windows-10-3c6669844031?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6669844031</guid>
            <category><![CDATA[laragon]]></category>
            <category><![CDATA[php-tutorial]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 10:47:25 GMT</pubDate>
            <atom:updated>2024-03-28T10:47:25.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Php Tutorial 2024] Lession 01 — Setup Php Development Environment in Windows 10</h3><p>Once upon a time, in the bustling world of web development, there existed a tale as old as time itself. It was the story of XAMPP and WAMP, two giants in the realm of local server environments. For years, developers relied on these stalwart companions to set up their development environments, to test their creations, and to bring their digital dreams to life.</p><p>But amidst the endless expanse of cyberspace, a new contender emerged. Its name was Laragon, a compact and powerful tool that promised to revolutionize the way developers worked on Windows machines. With its all-in-one approach and lightweight design, Laragon quickly captured the hearts and minds of developers around the world.</p><p>Gone were the days of wrestling with complex configurations and battling with compatibility issues. Laragon offered a seamless experience, effortlessly combining Apache, MySQL, PHP, and other essential components into a single, intuitive package. Setting up a local server environment became as simple as a few clicks, and developers found themselves free to focus on what truly mattered: crafting amazing websites and applications.</p><p>As word of Laragon spread far and wide, its popularity soared. Developers from all walks of life embraced this newfound tool, eager to experience the joys of hassle-free development. With each passing day, the community around Laragon grew stronger, fueled by a shared passion for innovation and creativity.</p><p>And so, dear reader, the story of XAMPP and WAMP faded into the annals of history, replaced by the legend of Laragon. It was a tale of progress, of adaptation, and of the endless quest for simplicity in an ever-evolving digital landscape. And as developers continued to build, create, and dream, Laragon stood as a shining beacon of hope, lighting the way towards a brighter future for all who dared to imagine.</p><h3>Setup Tools for development</h3><ol><li>Install PHP Environment -&gt; <a href="https://laragon.org/index.html">https://laragon.org/index.html</a></li><li>Install and Update composer -&gt; <a href="https://getcomposer.org/download/">https://getcomposer.org/download/</a></li><li>VsCode Extensions for PHP</li><li>Debug PHP with VSCode and Xdebug</li></ol><h3>Install PHP Environment</h3><blockquote><em>Install Laragon in Windows</em></blockquote><p>Download and install the appropriate versions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*X_T9KtM2uXCLsrG5" /></figure><p>Then launch laragon. Your www root directory will be placed in “C:\laragon\www”</p><p>When you create any folder in this www root directory, when launch wih laragon, it may help you to run at [your-folder-name].test</p><p>With Laragon, you can also manage multiple php versions on Window.</p><h3>Wanna use another version php with laragon</h3><p>Find your specific version at <a href="https://windows.php.net/downloads/releases/archives/">php archives</a> Usually, we use safe thread version so, for example, i wanna run with php 7.4.x</p><blockquote><em>9/29/2022 5:50 PM 26238674 php-7.4.32-Win32-vc15-x64.zip =&gt; this is my expected version</em></blockquote><p>Just download then extract and move it into “C:\laragon\bin\php”</p><p>And select your appropriate version</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*L3fO_yUeQNseCmms" /></figure><p>Remember to restart and check your version with command line like this</p><pre>php -v</pre><h3>Install and Update composer</h3><p>Laragon already included a built-in composer version. But you may wanna upgrade it, so just go to “C:\laragon\bin\composer”, and run these commands</p><pre>php -r &quot;copy(&#39;https://getcomposer.org/installer&#39;, &#39;composer-setup.php&#39;);&quot;<br>php -r &quot;if (hash_file(&#39;sha384&#39;, &#39;composer-setup.php&#39;) === &#39;dac665fdc30fdd8ec78b38b9800061b4150413ff2e3b6f88543c636f7cd84f6db9189d43a81e5503cda447da73c7e5b6&#39;) { echo &#39;Installer verified&#39;; } else { echo &#39;Installer corrupt&#39;; unlink(&#39;composer-setup.php&#39;); } echo PHP_EOL;&quot;<br>php composer-setup.php<br>php -r &quot;unlink(&#39;composer-setup.php&#39;);&quot;</pre><p>Then check your composer version</p><pre>composer --version</pre><h3>VsCode Extensions for PHP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*GQAtke-_XTQa-mVa" /></figure><ul><li>PHP Intelephense</li><li>PHP Namespace Resolver</li><li>PHPDoc Comment</li><li>PHP Debug</li></ul><h3>Install XDebug on Windows</h3><ul><li>Create index.php at your root folder</li><li>Edit content and replace with</li></ul><pre>&lt;?php<br>phpinfo();</pre><ul><li>View source and copy all of content</li><li>Paste in this <a href="https://xdebug.org/wizard">xdebug wizard form</a></li><li>Follow the instruction</li><li>Then enable xdebug extension witht laragon or edit your php.ini</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Br6wNdkJ2kmzrW--" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*-2mPF1pHcTyktFBL" /></figure><p>Then edit your php.ini, in my example “C:\laragon\bin\php\php-7.4.32-Win32-vc15-x64\php.ini”, and add the following lines at the end of file.</p><pre>[XDEBUG]<br>xdebug.mode = coverage,debug,develop<br>#xdebug.client_host = 127.0.0.1<br>xdebug.client_port = 9003<br>xdebug.start_with_request=yes</pre><p>Then create new debug config on vscode, you may see something like this</p><pre>{<br>  // Use IntelliSense to learn about possible attributes.<br>  // Hover to view descriptions of existing attributes.<br>  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>  &quot;version&quot;: &quot;0.2.0&quot;,<br>  &quot;configurations&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Listen for Xdebug&quot;,<br>      &quot;type&quot;: &quot;php&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;port&quot;: 9003<br>    },<br>    {<br>      &quot;name&quot;: &quot;Launch currently open script&quot;,<br>      &quot;type&quot;: &quot;php&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;program&quot;: &quot;${file}&quot;,<br>      &quot;cwd&quot;: &quot;${fileDirname}&quot;,<br>      &quot;port&quot;: 0,<br>      &quot;runtimeArgs&quot;: [&quot;-dxdebug.start_with_request=yes&quot;],<br>      &quot;env&quot;: {<br>        &quot;XDEBUG_MODE&quot;: &quot;debug,develop&quot;,<br>        &quot;XDEBUG_CONFIG&quot;: &quot;client_port=${port}&quot;<br>      }<br>    },<br>    {<br>      &quot;name&quot;: &quot;Launch Built-in web server&quot;,<br>      &quot;type&quot;: &quot;php&quot;,<br>      &quot;request&quot;: &quot;launch&quot;,<br>      &quot;runtimeArgs&quot;: [<br>        &quot;-dxdebug.mode=debug&quot;,<br>        &quot;-dxdebug.start_with_request=yes&quot;,<br>        &quot;-S&quot;,<br>        &quot;localhost:0&quot;<br>      ],<br>      &quot;program&quot;: &quot;&quot;,<br>      &quot;cwd&quot;: &quot;${workspaceRoot}&quot;,<br>      &quot;port&quot;: 9003,<br>      &quot;serverReadyAction&quot;: {<br>        &quot;pattern&quot;: &quot;Development Server \\(http://localhost:([0-9]+)\\) started&quot;,<br>        &quot;uriFormat&quot;: &quot;http://localhost:%s&quot;,<br>        &quot;action&quot;: &quot;openExternally&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>Press F5 to debug your website</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yURG4DCjN7ZKYb8v" /></figure><p>Now when you access your website vscode will jump in the selected breakpoint you set before.</p><p>Feel free to working with PHP on window 10.</p><p>Stay update with new articles at <a href="https://blog.phpguru.net/post/php-tutorial-2024-01-setup-php-development-environment-in-windows-10/">[Setup Php Development Environment in Windows 10]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6669844031" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Happy New Year 2024]]></title>
            <link>https://medium.com/@gmmiso88/happy-new-year-2024-3cb4e04763bd?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb4e04763bd</guid>
            <category><![CDATA[happy-new-year]]></category>
            <category><![CDATA[nextjsvietnam]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 11:59:33 GMT</pubDate>
            <atom:updated>2023-12-31T11:59:33.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*z6QVVHIqGxzTMYp7" /></figure><pre>#!/usr/bin/env node<br><br>const words = [&quot;Happy&quot;, &quot;New&quot;, &quot;Year&quot;, &quot;2024&quot;];<br>const message = {};<br>words.map((w, index) =&gt; {<br>  Reflect.set(message, index, w);<br>});<br><br>let happyNewYearMessage2024 = &quot;&quot;;<br>Reflect.ownKeys(message)<br>  .sort()<br>  .forEach((index) =&gt; {<br>    happyNewYearMessage2024 = `${happyNewYearMessage2024} ${Reflect.get(<br>      message,<br>      index<br>    )}`;<br>  });<br><br>console.log(happyNewYearMessage2024);</pre><p><a href="https://nextjsvietnam.com/post/happy-new-year-2024/">#happy new year 2024</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb4e04763bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Course Lesson 05 — Repository Pattern]]></title>
            <link>https://medium.com/@gmmiso88/nestjs-course-lesson-05-repository-pattern-a8146ec66b0d?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8146ec66b0d</guid>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 04:06:37 GMT</pubDate>
            <atom:updated>2023-07-25T04:06:37.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>NestJS Course Lesson 05 — Repository Pattern</h3><ul><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/lession05">Lession 05 Source Code</a></li></ul><h3>Lesson 05</h3><ol><li>A brief introduction to the repository pattern</li><li>Introduction to dependency injection in NestJS</li><li>Refactor the PetCategory code applying the repository pattern</li></ol><h3>Brief introduction to repository pattern</h3><p>In the previous post, you can see the following diagram in the MVC pattern</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*rvL4sa2aLDEAmxk2.png" /></figure><p>The controller uses the ORM’s Model directly to execute queries to the database.<br>This design will expose the following weaknesses:</p><ol><li>Reusability of queries: since it is located directly in the controller, it is almost impossible to reuse and share between different controllers.</li><li>Increasing the complexity of the controller, the more complex queries, the bigger the controller.</li><li>Unit Test implementation becomes difficult, because the database query part is mixed into the controller’s code</li></ol><p>To solve this problem, you should divide the code into different layers. The aim is to help increase the scalability and maintainability of the project.</p><p>That’s why the Repository Pattern is applied. To the definition of</p><blockquote><em>Repository is a class born to do the task of performing queries to the database.</em></blockquote><p>Because of the above characteristics, it only performs a single task, which is querying the database. Complex queries are encapsulated in this class. As a result, the 3 problems mentioned above will be thoroughly solved.</p><p>You can read more about Repository in this article about Domain Driven Design.</p><p>Here, let’s apply the above definition to practice with NestJS.<br>In the previous post, the Model got them directly in the Controller as follows</p><pre>const petCategories = await PetCategory.findAll();<br>await PetCategory.destroy({ where: { id } });<br>const newPetCategory = await PetCategory.create({ ...object });<br>const petCategory = await PetCategory.findByPk(id);<br>await petCategory.update(object);</pre><pre>// src\pet\repositories\pet-category.repository.ts<br>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { PetCategory } from &quot;../models/pet-category.model&quot;;</pre><pre>@Injectable()<br>export class PetCategoryRepository {<br>   findAll() {<br>     return PetCategory.findAll();<br>   }<br>}</pre><pre>// src/pet/pet.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { PetController } from &quot;./controllers/pet.controller&quot;;<br>import { ManagePetController } from &quot;./controllers/admin/manage-pet.controller&quot;;<br>import { ManagePetCategoryController } from &quot;./controllers/admin/manage-pet-category.controller&quot;;<br>import { ManagePetAttributeController } from &quot;./controllers/admin/manage-pet-attribute.controller&quot;;<br>import { nestjsFormDataModule } from &quot;nestjs-form-data&quot;;<br>import { PetCategoryRepository } from &quot;./repositories/pet-category.repository&quot;;<br>@Module({<br>   imports: [NestjsFormDataModule],<br>   controllers: [<br>     PetController,<br>     ManagePetController,<br>     ManagePetCategoryController,<br>     ManagePetAttributeController,<br>   ],<br>   // registered providers<br>   providers: [PetCategoryRepository],<br>})<br>export class PetModule {}</pre><pre>@Controller(&quot;admin/pet-categories&quot;)<br>export class ManagePetCategoryController {<br>   constructor(private petCategoryRepository: PetCategoryRepository) {}<br>   @Get(&quot;&quot;)<br>   @Render(&quot;pet/admin/manage-pet-category/list&quot;)<br>   async getList() {<br>     const petCategories = await this.petCategoryRepository.findAll();<br>     return {<br>       petCategories,<br>     };<br>   }<br>   // ...<br>}</pre><h3>Brief introduction to dependency injection</h3><p>Note in the above 3 code snippets, to use the repository, as you can see, you need to do 3 things:</p><ul><li>Declare the repository as an Injectable type</li><li>Declare the repository for the Providers list of the module</li><li>Inject the repository into the constructor of the controller you want to use</li></ul><p>If you are unfamiliar with the above concepts, please learn more details in the article about <a href="https://nextjsvietnam.com/post/nestjs-provider/">NestJS Provider</a>.</p><p>To put it simply, when you want to use a class in a module, instead of having to automatically initialize each time you use it, this will inadvertently cause this class to be initialized too many times unnecessarily. As well as writing code will become quite confusing.</p><p>Instead, if you apply the <strong>Dependency Injection</strong> pattern, you can easily solve this problem. Example of how dependency injection solves the above problem.</p><pre>import &quot;reflect-metadata&quot;;<br>import { injectable, inject, container } from &quot;tsyringe&quot;;</pre><pre>type ID = string | number;<br>interface Repository&lt;T&gt; {<br>   findOne(id: ID): T;<br>}<br>interface CrudService&lt;Model&gt; {<br>   findOne(id: ID): Model;<br>}</pre><pre>class User {<br>   id!: ID;<br>   firstName!: string;<br>   lastName!: string;<br>   constructor(payload: Partial&lt;User&gt;) {<br>     Object.assign(this, payload);<br>   }<br>}</pre><pre>class Role {<br>   id!: ID;<br>   name!: string;<br>   permissions: string[] = [];<br>   constructor(payload: Partial&lt;Role&gt;) {<br>     Object.assign(this, payload);<br>   }<br>}</pre><pre>class UserRepository implements Repository&lt;User&gt; {<br>   findOne(id: ID): User {<br>     const user = new User({<br>       id,<br>       firstName: &quot;Typescript&quot;,<br>       lastName: &quot;Master Class&quot;,<br>     });<br>     return user;<br>   }<br>}</pre><pre>class RoleRepository implements Repository&lt;Role&gt; {<br>   findOne(id: ID): Role {<br>     const role = new Role({<br>       id,<br>       name: &quot;Admin&quot;,<br>       permissions: [&quot;CreateUser&quot;, &quot;EditUser&quot;, &quot;RetrieveUser&quot;, &quot;DeleteUser&quot;],<br>     });<br>     return role;<br>   }<br>}</pre><pre>abstract class BaseService&lt;M, R extends Repository&lt;M&gt;&gt;<br>   implements CrudService&lt;M&gt;<br>{<br>   constructor(private repository: R) {}<br>   findOne(id: ID): M {<br>     return this.repository.findOne(id);<br>   }<br>}</pre><pre>@injectable()<br>class UserService extends BaseService&lt;User, UserRepository&gt; {<br>   constructor(<br>     @inject(UserRepository.name) userRepository: UserRepository,<br>     @inject(RoleRepository.name) private roleRepository: RoleRepository<br>   ) {<br>     super(userRepository);<br>   }</pre><pre>   retrievePermission(user: User) {<br>     return this.roleRepository.findOne(user.id);<br>   }<br>}</pre><pre>const main = () =&gt; {<br>   container.register(&quot;UserRepository&quot;, {<br>     useClass: UserRepository,<br>   });<br>   container.register(&quot;RoleRepository&quot;, {<br>     useClass: RoleRepository,<br>   });<br>   const userService = container.resolve(UserService);<br>   const user = userService.findOne(1);<br>   const permissions = userService.retrievePermission(user);<br>   console.log(user, permissions);<br>};</pre><pre>main();</pre><p>In the code illustrated above, you can clearly see, the service will depend on the repository. However, the initialization of the repository will be delegated. To better understand this pattern, you can learn in detail through the article <a href="https://nextjsvietnam.com/post/learn-enough-oop-to-be-dangerous/">Learn Enough Oop to Be Dangerous</a></p><p>Thus, it can be seen that when working with NestJS, creating a class and embedding another class to use is quite simple, isn’t it.</p><p>In addition to creating a repository actively as above, in the nestjs ecosystem, you can use the following way. Use the model itself as a repository</p><blockquote><em>Create provider using custom token and useValue</em></blockquote><p>The reason is that this repository will use the static methods of the model. So initializing this dependency will use the Model itself as the value.</p><pre>import { PetCategory } from &quot;../models/pet-category.model&quot;;</pre><pre>export const PetCategoryInjectionKey = &quot;Pet_Category&quot;;<br>export const PetCategoryProvider = {<br>   provide: PetCategoryInjectionKey,<br>   useValue: PetCategory,<br>};</pre><pre>// src/pet/pet.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { PetController } from &quot;./controllers/pet.controller&quot;;<br>import { ManagePetController } from &quot;./controllers/admin/manage-pet.controller&quot;;<br>import { ManagePetCategoryController } from &quot;./controllers/admin/manage-pet-category.controller&quot;;<br>import { ManagePetAttributeController } from &quot;./controllers/admin/manage-pet-attribute.controller&quot;;<br>import { nestjsFormDataModule } from &quot;nestjs-form-data&quot;;<br>import { PetCategoryRepository } from &quot;./repositories/pet-category.repository&quot;;<br>import { PetCategoryProvider } from &quot;./providers/pet-category.provider&quot;;<br>@Module({<br>   imports: [NestjsFormDataModule],<br>   controllers: [<br>     PetController,<br>     ManagePetController,<br>     ManagePetCategoryController,<br>     ManagePetAttributeController,<br>   ],<br>   providers: [PetCategoryRepository, PetCategoryProvider],<br>})<br>export class PetModule {}</pre><pre>import { PetCategoryInjectionKey } from &#39;./../../providers/pet-category.provider&#39;;<br>import {<br>   Body,<br>   controller,<br>   Get,<br>   render,<br>   Inject,<br>} from &#39;@nestjs/common&#39;;<br>@Controller(&#39;admin/pet-categories&#39;)<br>export class ManagePetCategoryController {<br>   constructor(<br>     @Inject(PetCategoryInjectionKey)<br>     private defaultPetCategoryRepository: typeof PetCategory,<br>   ) {}<br>   @Get(&#39;&#39;)<br>   @Render(&#39;pet/admin/manage-pet-category/list&#39;)<br>   async getList() {<br>     const petCategories = await this.defaultPetCategoryRepository.findAll();<br>     return {<br>       petCategories,<br>     };<br>   }</pre><p>However, method #2 does not completely solve the problem like method #1, although it seems that an additional class repository appears when used in a controller. But writing the query will still be entirely in the controller.<br>Although it looks like the controller and model will be more independent, the essence of the problem is still not solved.<br>Therefore, when applied in real projects, you should choose method 1, because there will be many cases where complex queries are needed, instead of just CRUD.</p><h3>Refactor code for Pet Website application</h3><p>In this section, you will practice separating code into separate classes, to ensure that the application’s code base has a consistent, coherent structure, and has a logical separation that helps the code base become:</p><ul><li>Easy to maintain</li><li>Easy to test</li><li>Easy to add new/change</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wvfbmvPhOFwKtS4g.png" /></figure><p>In the above model, the components are defined as follows:</p><blockquote><em>DTO : data transfer object</em></blockquote><ol><li>Request DTO</li></ol><blockquote><em>This part is the data received from the client</em></blockquote><ol><li>Response DTO</li></ol><blockquote><em>This part is the data after a process of processing through different steps that will be bound to the </em><strong><em>View</em></strong><em> section</em></blockquote><ol><li>Controller</li></ol><blockquote><em>This part is the part that receives data from the client side and performs the next steps in the process. Responsible for connecting to the service to get the ResponseDTO and read the template from the View and render the final result to the user.</em></blockquote><ol><li>Service</li></ol><blockquote><em>This part is responsible for receiving data from the Controller and executing the business logic. Including: checking input data, transforming data if necessary, connecting with other services to perform processing operations, connecting to corresponding repositories to interact with the stored data layer. The goal is to provide aggregated data after business execution for the Controller</em></blockquote><ol><li>Entity</li></ol><blockquote><em>The main business object, including the properties that represent the object in the application</em></blockquote><ol><li>Model</li></ol><blockquote><em>Object mapping of data stored in the database.</em></blockquote><p>Usually, it is possible to use the same class for both Entity and Model because these two objects are quite similar.</p><ol><li>Repository</li></ol><blockquote><em>This middle class is responsible for performing queries to the database</em></blockquote><p>Following the above structure, please refactor the code of Pet Website.</p><p>Feel free to read full article about <a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs-bai-05-repository-pattern/">NestJS Course Lesson 05 — Repository Pattern</a></p><p><a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs-bai-05-repository-pattern/">khóa học nestjs</a>, <a href="https://nextjsvietnam.com/categories/nestjs-tutorial/">khoa hoc nestjs</a>, <a href="https://nextjsvietnam.com/">nextjs vietnam</a>, [nestjs tips and tricks)[<a href="https://nextjsvietnam.com/">https://nextjsvietnam.com/</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8146ec66b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS Course — Lesson 03 — Props and States]]></title>
            <link>https://medium.com/@gmmiso88/reactjs-course-lesson-03-props-and-states-cdd0b507acbf?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd0b507acbf</guid>
            <category><![CDATA[reactjs-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[react-js-training]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Fri, 21 Jul 2023 11:31:24 GMT</pubDate>
            <atom:updated>2023-07-21T11:31:24.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>ReactJS Course — Lesson 03 — Props and States</h3><p><a href="https://nextjsvietnam.com/categories/reactjs/">#reactjs</a> <a href="https://nextjsvietnam.com/categories/reactjs-tutorial/">#khóa học reactjs</a> <a href="https://nextjsvietnam.com/">#nextjsvietnam</a></p><p><strong>Note</strong>: All source code for this course is publicly available on github at <a href="https://github.com/misostack/reactjs-tutorial-2023/tree/lession03">ReactJS Tutorial 2023</a></p><h3>Lesson 03</h3><ol><li>Learn the theory of props, state, hooks and illustration</li><li>Learn the theory of how to organize data structures in applications and illustrate</li><li>Summary</li></ol><p>In the previous article, you have learned the structure of a ReactJS application which is a combination of components.</p><h3>Learn about props, state, hooks through examples</h3><ol><li>Design button “New Link” and LinkFormComponent</li></ol><ul><li>Install bootstrap</li><li>Handle Event when pressing “New Link” button will open Modal without input form for new link</li><li>In the input form for the new link, it is required to enter the link, the title part if the user leaves it blank, use the entered link as the title.</li><li>When clicking Close/Esc will close the modal. When reopening the Modal for New Link, the form data must be empty.</li><li>When you click Save Changes in the main screen, it will display the JSON format of the added links.</li></ul><blockquote><em>Using bootstrap</em></blockquote><pre>npm install bootstrap sass --save</pre><blockquote><em>index.html</em></blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>   &lt;head&gt;<br>     &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>     &lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;/vite.svg&quot; /&gt;<br>     &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>     &lt;title&gt;%VITE_APP_NAME% - %MODE%&lt;/title&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>     &lt;div id=&quot;root&quot; class=&quot;container&quot;&gt;&lt;/div&gt;<br>     &lt;script type=&quot;module&quot; src=&quot;/src/main.jsx&quot;&gt;&lt;/script&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote><em>main.jsx</em></blockquote><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import App from &quot;./App.jsx&quot;;<br>// Bootstrap Bundle JS<br>import &quot;bootstrap/dist/js/bootstrap.bundle.min&quot;;<br>// reset css<br>import &quot;./index.scss&quot;;</pre><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>   &lt;React.StrictMode&gt;<br>     &lt;App /&gt;<br>   &lt;/React.StrictMode&gt;<br>);</pre><blockquote><em>index.scss</em></blockquote><pre>$primary: #176d16;<br>$danger: #ff4136;</pre><pre>@import &quot;node_modules/bootstrap/scss/bootstrap&quot;;</pre><h4>Event Handler in ReactJS</h4><pre>&lt;a<br>   href=&quot;https://nextjsvietnam.com&quot;<br>   className=&quot;btn btn-primary&quot;<br>   onClick={(e) =&gt; {<br>     e.preventDefault();<br>     alert(`You&#39;re going to redirect to ${e.target.href}`);<br>   }}<br>&gt;<br>   Event Handler<br>&lt;/a&gt;</pre><h4>Props</h4><blockquote><em>In ReactJS, components often use props to communicate with each other. Parent components will usually pass data to child components via props. In addition, props also includes HTML attributes, values in Javascript such as: objects, arrays, including functions.</em></blockquote><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Counter = ({ number, children, ...props }) =&gt; {<br>   return (<br>     &lt;&gt;<br>       &lt;a {...props}&gt;<br>         Counter Name:{children}<br>         &lt;br /&gt;<br>         Value: {number}<br>       &lt;/a&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>const Lesson003 = () =&gt; {<br>   const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];<br>   return (<br>     &lt;&gt;<br>       {values.map((v, index) =&gt; (<br>         &lt;Counter key={index} number={v} className=&quot;btn btn-primary&quot;&gt;<br>           Counter {index + 1}<br>         &lt;/Counter&gt;<br>       ))}<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>There are 3 points to keep in mind here when using props:</p><ol><li>All attributes passed as attributes of a tag/component are included in props. However, use the spread operator to select certain properties, this makes it easy for the editor to assist you in the coding process.</li><li>In the above example you will see the appearance of <strong>chidren</strong>, this keyword means that the content inside the 2 opening and closing tags of the component will be assigned to the prop with the key <strong>children</strong>.</li><li>Props are readonly, never try to change the value of props (immutable). Always use the underlying state when a variable type is needed to change the value each time the user interacts.</li></ol><p>One note, when rendering a list in ReactJS, we will see the following error appear on the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*2PUJ0Kcp8If4k-M1.png" /></figure><p>The reason is that in the design of ReactJS, in order to optimize rendering and DOM updates, when rendering a list of items, assigning a unique key to each element in the array, will help ReactJS optimize rendering when an item is added/removed/updated.</p><h4>State</h4><blockquote><em>It is essentially the component’s memory, representing the current state of the component and will change when the user interacts with the component</em></blockquote><p>Consider the following example</p><pre>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   let counter = 1;<br>   console.log(&quot;Before render&quot;);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 1}`);<br>           counter += 1;<br>           console.log(&quot;After counter increased!&quot;, counter);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>As we have seen, the event handler is very similar to handling an event on the DOM, just a little different in syntax, is that instead of calling the function immediately, in JSX you need to assign an event to a function. This function can be an anonymous function as in the example, or a previously declared function.</p><pre>&lt;button onclick=&quot;myFunction()&quot;&gt;Click me&lt;/button&gt;</pre><p>Looking at the above code, you will think, when the counter variable changes, on the screen now, you will see its new value. However, keep an eye on the console.log and the results of each click of the Increase counter button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*DqsyFmczgm1p0opH.png" /></figure><p>The expected result is that after each counter mutate, console.log will record an extra line of “Before render”. And the counter on the interface will also be updated.</p><p>The answer is, React Component has no reason to re-render, it just re-renders if and only when <strong>state</strong> changes. Below is the syntax to declare and use state in ReactJS.</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [counter, setCounter] = useState(0);<br>   console.log(&quot;Before render, counter:&quot;, counter);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 1}`);<br>           setCounter(counter + 1);<br>           console.log(&quot;After counter increased!&quot;, counter);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Th2ApkIpcPOXlxcQ.png" /></figure><p>After rewriting the original code, using the syntax in React to declare and update the state. We notice three things:</p><ol><li>The state cannot be updated directly, only the provided setState function can be used.</li><li>When the setState function is called, the value of state does not change immediately.</li><li>After the Component is re-rendered, we will see the new value of the state.</li><li>If the state is an object, it should be noted that the new value of the state must form a new object, then React will recognize the changed state and re-render (because the object in javascript is always referenced to a fixed address at initialization and during the value change process, this reference address remains unchanged).</li></ol><p>Suppose, we call the state update function consecutively, what will happen:</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [counter, setCounter] = useState(0);<br>   console.log(&quot;Before render, counter:&quot;, counter);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 1}`);<br>           setCounter(counter + 1);<br>           setCounter(counter + 2);<br>           setCounter(counter + 3);<br>           console.log(&quot;After counter increased!&quot;, counter);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>Maybe 6 or so? As a result, only setCounter(counter+3) is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FjjtVNw41MFOY4EZ.png" /></figure><p>Explanation: In an event, when the state update happens, ReactJS will collect these updates and execute it once, at this time the state counter will be a fixed value in each update event, so even though the previous state update events of +1,+2 are performed, but at step number +3, the counter value is still taken from the original value, so the result will be as we have seen.<br>Let’s test updating 2 separate states in the same event and check how many times ReactJS will render.</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [counter, setCounter] = useState(0);<br>   const [counter2, setCounter2] = useState(1);<br>   console.log(&quot;Before render, counter:&quot;, counter, &quot;counter2:&quot;, counter2);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;h3&gt;Counter2: {counter2}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 2}`);<br>           console.log(`Increase counter from ${counter2} to ${counter2 + 3}`);<br>           setCounter(counter + 2);<br>           setCounter2(counter2 + 3);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*e_hzeShmWRuytVQM.png" /></figure><p>If instead of using state value directly in component, and update state using callback function like below</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [counter, setCounter] = useState(0);<br>   const [counter2, setCounter2] = useState(1);<br>   console.log(&quot;Before render, counter:&quot;, counter, &quot;counter2:&quot;, counter2);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;h3&gt;Counter2: {counter2}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 2}`);<br>           console.log(`Increase counter from ${counter2} to ${counter2 + 3}`);<br>           setCounter((counter) =&gt; counter + 2);<br>           setCounter((counter) =&gt; counter + 4);<br>           setCounter2((counter2) =&gt; counter2 + 3);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>The results are exactly as described.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*2AULIS02nL5UdRC9.png" /></figure><p>Further testing with setTimeOut,</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [counter, setCounter] = useState(0);<br>   const [counter2, setCounter2] = useState(1);<br>   console.log(&quot;Before render, counter:&quot;, counter, &quot;counter2:&quot;, counter2);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;Counter: {counter}&lt;/h3&gt;<br>       &lt;h3&gt;Counter2: {counter2}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           console.log(`Increase counter from ${counter} to ${counter + 2}`);<br>           console.log(`Increase counter from ${counter2} to ${counter2 + 3}`);<br>           setCounter((counter) =&gt; counter + 2);<br>           setCounter((counter) =&gt; counter + 4);<br>           setTimeout(() =&gt; {<br>             setCounter((counter) =&gt; counter + 6);<br>           }, 0);<br>           setCounter2((counter2) =&gt; counter2 + 3);<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>As a result, we have 2 renders, because the update of state counter + 6 takes place in another process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*LiR15pmSC05sF4Bm.png" /></figure><p>Same test with object for statestate</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [stateObject, setStateObject] = useState({<br>     a: {<br>       b: {<br>         c: 1,<br>       },<br>     },<br>   });<br>   console.log(&quot;Before render, stateObject.a.b.c:&quot;, stateObject.a.b.c);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;StateObject: {JSON.stringify(stateObject)}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           setStateObject((obj) =&gt; {<br>             console.log(obj.a.b.c, &quot;obj === stateObject&quot;, obj === stateObject);<br>             obj.a.b.c += 1;<br>             return obj;<br>           });<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>As a result, even though we see the value of c has changed, in fact the UI still does not re-render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*fCl7xFGCGAKuDBPQ.png" /></figure><p>Therefore, mutating the object directly and the resulting change still refer to the same object, will make the React Component not aware that it will have to re-render, because it performs the comparison between the two objects.<br>Therefore, it is imperative that you do not change this object directly, but rather create an object consisting of the values of the old object mixed with the new changed value.</p><pre>import { useState } from &quot;react&quot;;<br>import enviroment from &quot;./shared/environment&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [stateObject, setStateObject] = useState({<br>     a: {<br>       b: {<br>         c: 1,<br>       },<br>     },<br>   });<br>   console.log(&quot;Before render, stateObject.a.b.c:&quot;, stateObject.a.b.c);<br>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State and Event&lt;/h2&gt;<br>       &lt;h3&gt;StateObject: {JSON.stringify(stateObject)}&lt;/h3&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           setStateObject((obj) =&gt; {<br>             console.log(obj.a.b.c, &quot;obj === stateObject&quot;, obj === stateObject);<br>             return {<br>               ...obj,<br>               a: {<br>                 b: {<br>                   c: obj.a.b.c + 1,<br>                 },<br>               },<br>             };<br>           });<br>         }}<br>       &gt;<br>         Increase counter<br>       &lt;/button&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*_lwcaMwY7Glv50nc.png" /></figure><p>Now both on the UI, and on the console, the value of c is updated accordingly.</p><blockquote><em>How to get the value of form input</em></blockquote><pre>import { useState } from &quot;react&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [input, setInput] = useState(&quot;&quot;);<br>   const [items, setItems] = useState([]);</pre><pre>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State Array&lt;/h2&gt;<br>       &lt;div className=&quot;mb-3&quot;&gt;<br>         &lt;label htmlFor=&quot;exampleFormControlInput1&quot; className=&quot;form-label&quot;&gt;<br>           Item name<br>         &lt;/label&gt;<br>         &lt;input<br>           value={input}<br>           onChange={(e) =&gt; {<br>             setInput(e.target.value);<br>           }}<br>           type=&quot;email&quot;<br>           className=&quot;form-control&quot;<br>           id=&quot;exampleFormControlInput1&quot;<br>           placeholder=&quot;name&quot;<br>         /&gt;<br>       &lt;/div&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           setItems((items) =&gt; {<br>             return [...items, input];<br>           });<br>         }}<br>       &gt;<br>         Add new item<br>       &lt;/button&gt;<br>       &lt;ul&gt;<br>         {items.map((item, index) =&gt; (<br>           &lt;li key={index}&gt;{item}&lt;/li&gt;<br>         ))}<br>       &lt;/ul&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*pqdhLTvIKOGLOgTn.png" /></figure><p>So we can see that by using state, and the onChange event, you will be able to synchronize the user input and the state of this input. Thanks to the mechanism of ReactJS, in the picture you only see the re-rendered part is the content of the input, not the whole, which makes the application so smooth.</p><blockquote><em>Let’s try with state as array</em></blockquote><pre>&lt;button<br>   type=&quot;button&quot;<br>   className=&quot;btn btn-primary&quot;<br>   onClick={(e) =&gt; {<br>     e.preventDefault();<br>     setItems((items) =&gt; {<br>       return [...items, input];<br>     });<br>   }}<br>&gt;<br>   Add new item<br>&lt;/button&gt;</pre><p>Through the above examples, we can conclude the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*JdBMUZjxtjzljFmR.png" /></figure><blockquote><em>However, the above way of writing makes the code look quite complicated and difficult to maintain. You can use the immutable library to still ensure the immutable state of the state, but when you write the code, it looks like it’s mutating.</em></blockquote><pre>npm install use-immer --save</pre><pre>import { useState } from &quot;react&quot;;<br>import { useImmer } from &quot;use-immer&quot;;</pre><pre>const Lesson003 = () =&gt; {<br>   const [input, setInput] = useState(&quot;&quot;);<br>   const [items, setItems] = useImmer([]);</pre><pre>   return (<br>     &lt;&gt;<br>       &lt;h2&gt;State Array&lt;/h2&gt;<br>       &lt;div className=&quot;mb-3&quot;&gt;<br>         &lt;label htmlFor=&quot;exampleFormControlInput1&quot; className=&quot;form-label&quot;&gt;<br>           Item name<br>         &lt;/label&gt;<br>         &lt;input<br>           value={input}<br>           onChange={(e) =&gt; {<br>             setInput(e.target.value);<br>           }}<br>           type=&quot;email&quot;<br>           className=&quot;form-control&quot;<br>           id=&quot;exampleFormControlInput1&quot;<br>           placeholder=&quot;name&quot;<br>         /&gt;<br>       &lt;/div&gt;<br>       &lt;button<br>         type=&quot;button&quot;<br>         className=&quot;btn btn-primary&quot;<br>         onClick={(e) =&gt; {<br>           e.preventDefault();<br>           setItems((items) =&gt; {<br>             items.push(input);<br>           });<br>         }}<br>       &gt;<br>         Add new item<br>       &lt;/button&gt;<br>       &lt;ul&gt;<br>         {items.map((item, index) =&gt; (<br>           &lt;li key={index}&gt;{item}&lt;/li&gt;<br>         ))}<br>       &lt;/ul&gt;<br>     &lt;/&gt;<br>   );<br>};</pre><pre>export default Lesson003;</pre><p>This new code looks much cleaner, doesn’t it?</p><h4>The process of rendering a ReactJS Component will proceed as follows:</h4><blockquote><em>Trigger -&gt; Render -&gt; Commit</em></blockquote><p><strong>Trigger:</strong></p><ul><li>When the application is initialized at this step, ReactJS will embed the application in the DOM node root, and call the <strong>render</strong> method of the components.</li><li>Re-render: every time the component updates its state, it will re-render itself, which leads to its children components re-rendering as well.</li></ul><p><strong>Render</strong>:</p><p>As mentioned above, when the application initializes, React will call the root component to perform the rendering.</p><ul><li>For the next time, React will actually call the function components whose state update triggers this rendering.</li></ul><p><strong>Commit</strong>:</p><ul><li>When the application initializes, after the root component renders successfully, React will now append all the generated DOM nodes to the DOM tree.</li><li>For subsequent iterations, React will do the comparison and only update the DOM tree if there is actually a change.</li></ul><p>So you have an overview of state, props in ReactJS and how ReactJS re-renders components when state changes.</p><h3>Practice building a link management application</h3><h4>Application requirements</h4><p>In real application, we need to solve more conundrums. Within the scope of this lesson, we seek to answer the following questions.</p><p>Suppose, you have to build a small application, to manage a list of links.<br>Each link can be: Website Link, Image(png/jpg/jpeg), Youtube Link.</p><p>The application will include a single screen, adding and editing tasks will open a modal that allows the user to enter/change information, after saving, the information in the list will be updated.</p><p><strong>Main features of the application include:</strong></p><ul><li>Add, Edit, Delete Link</li><li>Display links in 3 formats: website (link form with entered title, if title is blank, use link), image (image format with entered title, if blank, use link), youtube link (iframe with embed link)</li><li>Store application information on the user’s machine, so that when the application is closed and reopened, the saved information still exists.</li></ul><p><strong>Interface requirements are as follows</strong></p><blockquote><em>Home screen</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ijNhLCmJCahkw7Z9.png" /></figure><blockquote><em>Modal add, edit</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UPDE9u69QgJtzkQh.png" /></figure><p>Feel free to read full course at <a href="https://nextjsvietnam.com/post/khoa-hoc-reactjs-bai-03/">ReactJS Course 2023</a></p><p>From <a href="https://nextjsvietnam.com/post/khoa-hoc-reactjs-bai-03/">Khóa Học ReactJS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd0b507acbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Course Lesson 04 — Model and Repository Pattern]]></title>
            <link>https://medium.com/@gmmiso88/nestjs-course-lesson-04-model-and-repository-pattern-bce194925884?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/bce194925884</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 01:51:41 GMT</pubDate>
            <atom:updated>2023-07-06T14:44:31.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>NestJS Course Lesson 04 — Model and Repository Pattern</h3><p>#nestjs <a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs/">#nestjs-tutorial</a> #khoa-hoc-nestjs #nestjs-mvc</p><h3>Source Code</h3><ul><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/lession04">Lession 04 Source Code</a></li></ul><h3>Lesson 04</h3><ol><li>Brief introduction to one of popular ORM — Sequelize</li><li>Learn about the ActiveRecord Pattern</li><li>How to create database schema with Sequelize in NestJS</li><li>How to add seeding data with Sequelize in NestJS</li></ol><h3>1. Configure NestJS to work with MySQL via Sequelize</h3><p>First you need to create the database first<br>Database name : <strong>nestjs_tutorial_2023</strong></p><pre>CREATE DATABASE `nestjs_tutorial_2023` CHARACTER SET &#39;utf8mb4&#39; COLLATE &#39;utf8mb4_bin&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*uEVUp8ZwbEovPWzV.png" /></figure><ul><li>Connect to MYSQL using Sequelize</li><li>Connect to PostgreSQL using TypeORM</li><li>Connect to MongoDB using Mongoose</li></ul><p><strong>1.1. Connect to MYSQL using Sequelize</strong></p><p>Install packages</p><pre>npm install --save @nestjs/sequelize sequelize sequelize-typescript mysql2<br>npm install --save-dev @types/sequelize<br>npm install --save-dev sequelize-cli<br>npx sequelize-cli init</pre><p>In this part, I would like to introduce to you 3 main steps to work with databases:</p><ol><li>[x] Establish connection</li><li>[x] Declare model</li><li>[x] Database migration directory structure — initialize, update database schema</li></ol><blockquote><em>Set up connection</em></blockquote><pre>// src/app.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { ServeStaticModule } from &quot;@nestjs/serve-static&quot;;<br>import { join } from &quot;path&quot;;<br>import { PetModule } from &quot;./pet/pet.module&quot;;<br>import { SequelizeModule } from &quot;@nestjs/sequelize&quot;;</pre><pre>@Module({<br>   imports: [<br>     // public folder<br>     ServeStaticModule.forRoot({<br>       rootPath: join(process.cwd(), &quot;public&quot;),<br>       serveRoot: &quot;/public&quot;,<br>     }),<br>     PetModule,<br>     SequelizeModule.forRoot({<br>       dialect: &quot;mysql&quot;,<br>       host: &quot;localhost&quot;,<br>       port: 3306,<br>       username: &quot;root&quot;,<br>       password: &quot;123456&quot;,<br>       database: &quot;nestjs_tutorial_2023&quot;,<br>       models: [],<br>     }),<br>   ],<br>   providers: [],<br>})<br>export class AppModule {}</pre><blockquote><em>Model declaration</em></blockquote><p><strong>Model in ORM:</strong></p><ul><li>It is the mapping of an entity in the database, through the ORM we only need to work with the methods of the Model, the rest are SQL/NoSQL statements that will be handled by the ORM. The advantage is that programming becomes easier and more consistent. The downside is that sometimes some queries will be slow and difficult to implement complex queries. However, in that case ORM still supports them to perform traditional SQL/NoSQL queries.</li></ul><pre>&quot;use strict&quot;;</pre><pre>import { PetCategory } from &quot;src/pet/models/pet-category.model&quot;;</pre><pre>/** @type {import(&#39;sequelize-cli&#39;).Migration} */</pre><pre>module.exports = {<br>   async up(queryInterface, Sequelize) {<br>     /**<br>      * Add altering commands here.<br>      *<br>      * Example:<br>      * await queryInterface.createTable(&#39;users&#39;, { id: Sequelize.INTEGER });<br>      */<br>     await queryInterface.createTable(&quot;pet_categories&quot;, {<br>       id: {<br>         type: Sequelize.UUID,<br>         defaultValue: Sequelize.UUIDV4,<br>         primaryKey: true,<br>       },<br>       name: {<br>         type: Sequelize.STRING(60),<br>         allowNull: false,<br>       },<br>       createAt: {<br>         type: Sequelize.DATE,<br>         defaultValue: Sequelize.fn(&quot;NOW&quot;),<br>       },<br>       updatedAt: {<br>         type: Sequelize.DATE,<br>         defaultValue: Sequelize.fn(&quot;NOW&quot;),<br>       },<br>     });<br>   },</pre><pre>   async down(queryInterface, Sequelize) {<br>     /**<br>      * Add reverting commands here.<br>      *<br>      * Example:<br>      * await queryInterface.dropTable(&#39;users&#39;);<br>      */<br>     await queryInterface.dropTable(&quot;pet_categories&quot;);<br>   },<br>};</pre><blockquote><em>Adjust the config to use the model and use the database uri</em></blockquote><pre>// src/app.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { ServeStaticModule } from &quot;@nestjs/serve-static&quot;;<br>import { join } from &quot;path&quot;;<br>import { PetModule } from &quot;./pet/pet.module&quot;;<br>import { SequelizeModule } from &quot;@nestjs/sequelize&quot;;<br>import models from &quot;./pet/models&quot;;</pre><pre>@Module({<br>   imports: [<br>     // public folder<br>     ServeStaticModule.forRoot({<br>       rootPath: join(process.cwd(), &quot;public&quot;),<br>       serveRoot: &quot;/public&quot;,<br>     }),<br>     PetModule,<br>     SequelizeModule.forRoot({<br>       uri: &quot;mysql://root:123456@localhost/nestjs_tutorial_2023&quot;,<br>       dialect: &quot;mysql&quot;,<br>       models: models,<br>     }),<br>   ],<br>   providers: [],<br>})<br>export class AppModule {}</pre><blockquote><em>Database migration directory structure — initialize, update database schema</em></blockquote><p>Some explanation why we need to use sequelize-cli to update database.<br>During project development, when there is a data table that needs to add/delete or update columns in the table. The most direct way is SQL statements, although we can still manage which statements have run or not and shared with team members or people in charge of deploying products on production environment.</p><p>In today’s modern ORMs, to unify how and standardize, we will usually use the cli of these ORMs related to creating/editing databases, tables.<br>And perform the migration via command lines. The structure of the data tables will be implemented through code — for consistency with the model managed by the ORM.</p><p>After running the following default command of sequelize-cli we will have the following default directory structure.</p><pre>npx sequelize-cli init</pre><pre>config<br>   database.json<br>db<br>   models<br>   seeders<br>   migrations</pre><blockquote><strong><em>.sequelizerc</em></strong></blockquote><pre>// .sequelizerc</pre><pre>const path = require(&quot;path&quot;);</pre><pre>module.exports = {<br>   config: path.resolve(&quot;config&quot;, &quot;database.json&quot;),<br>   &quot;models-path&quot;: path.resolve(&quot;db&quot;, &quot;models&quot;),<br>   &quot;seeders-path&quot;: path.resolve(&quot;db&quot;, &quot;seeders&quot;),<br>   &quot;migrations-path&quot;: path.resolve(&quot;db&quot;, &quot;migrations&quot;),<br>};</pre><p>However, to match the current structure of the project, we need to adjust a bit as follows</p><pre>src<br>     database<br>         config<br>             config.ts<br>     migrations<br>         *.ts<br>     seeds<br>         *.ts</pre><blockquote><strong><em>.sequelizerc</em></strong></blockquote><pre>const path = require(&quot;path&quot;);</pre><pre>module.exports = {<br>   config: path.resolve(&quot;./dist/database/config/config.js&quot;),<br>   &quot;seeders-path&quot;: path.resolve(&quot;./dist/database/seeders&quot;),<br>   &quot;migrations-path&quot;: path.resolve(&quot;./dist/database/migrations&quot;),<br>};</pre><p>Here, instead of running the source version directly, we will run their build</p><pre>// config.ts<br>module.exports = {<br>   production: {<br>     url: &quot;mysql://root:123456@localhost/nestjs_tutorial_2023&quot;,<br>     dialect: &quot;mysql&quot;,<br>   },<br>};</pre><pre>// src/pet/models/pet-category.model<br>import { Column, DataType, Model, Table } from &quot;sequelize-typescript&quot;;</pre><pre>@Table({<br>   tableName: &quot;pet_categories&quot;,<br>})<br>export class PetCategory extends Model {<br>   @Column({<br>     primaryKey: true,<br>     type: DataType.UUID,<br>     defaultValue: DataType.UUIDV4,<br>   })<br>   id?: string;</pre><pre>   @Column({<br>     type: DataType.STRING(60),<br>     allowNull: false,<br>   })<br>   name: string;<br>}</pre><pre>// src\database\migrations\20230704043449-create-pet-category-table.ts<br>&quot;use strict&quot;;</pre><pre>import { PetCategory } from &quot;src/pet/models/pet-category.model&quot;;</pre><pre>/** @type {import(&#39;sequelize-cli&#39;).Migration} */</pre><pre>module.exports = {<br>   async up(queryInterface, Sequelize) {<br>     /**<br>      * Add altering commands here.<br>      *<br>      * Example:<br>      * await queryInterface.createTable(&#39;users&#39;, { id: Sequelize.INTEGER });<br>      */<br>     await queryInterface.createTable(&quot;pet_categories&quot;, {<br>       id: {<br>         type: Sequelize.UUID,<br>         defaultValue: Sequelize.UUIDV4,<br>         primaryKey: true,<br>       },<br>       name: {<br>         type: Sequelize.STRING(60),<br>         allowNull: false,<br>       },<br>     });<br>   },</pre><pre>   async down(queryInterface, Sequelize) {<br>     /**<br>      * Add reverting commands here.<br>      *<br>      * Example:<br>      * await queryInterface.dropTable(&#39;users&#39;);<br>      */<br>     await queryInterface.dropTable(&quot;pet_categories&quot;);<br>   },<br>};</pre><h3>Special note for the model here</h3><p>Because the PetCategory Model in the example inherits from the Model from sequelize, it will inherit some predefined fields, although in the code of the PetCategory Model we do not see them appear.<br>Therefore, when creating a migration script for PetCategory, you should note these two default columns.</p><pre>export declare abstract class Model&lt;TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes&gt; extends OriginModel&lt;TModelAttributes, TCreationAttributes&gt; {<br>     id?: number | any;<br>     createAt?: Date | any;<br>     updatedAt?: Date | any;<br>     deletedAt?: Date | any;<br>     version?: number | any;<br>     static isInitialized: boolean;</pre><p><strong>Some common commands</strong></p><pre>$ npx sequelize-cli --help</pre><pre>Sequelize CLI [Node: 16.19.1, CLI: 6.6.1, ORM: 6.32.1]</pre><pre>sequelize &lt;command&gt;</pre><pre>Commands:<br>   sequelize db:migrate Run pending migrations<br>   sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps<br>   sequelize db:migrate:status List the status of all migrations<br>   sequelize db:migrate:undo Reverts a migration<br>   sequelize db:migrate:undo:all Revert all migrations ran<br>   sequelize db:seed Run specified seeder<br>   sequelize db:seed:undo Deletes data from the database<br>   sequelize db:seed:all Run every seeder<br>   sequelize db:seed:undo:all Deletes data from the database<br>   sequelize db:create Create database specified by configuration<br>   sequelize db:drop Drop database specified by configuration<br>   sequelize init Initializes project<br>   sequelize init:config Initializes configuration<br>   sequelize init:migrations Initializes migrations<br>   sequelize init:models Initialize models<br>   sequelize init:seeders Initializes seeders<br>   sequelize migration:generate Generates a new migration file<br>   sequelize migration:create Generates a new migration file<br>   sequelize model:generate Generates a model and its migration<br>   sequelize model:create Generates a model and its migration<br>   sequelize seed:generate Generates a new seed file<br>   sequelize seed:create Generates a new seed file</pre><p><strong>I would like an example command to make a migration file, then build, and run</strong></p><pre># create migration<br>npx sequelize-cli migration:create --name create-pet-category-table --migrations-path ./src/database/migrations<br># build<br>npm run build<br># run migration<br>npx sequelize-cli db:migrate --env production</pre><p>Note that if env is not specified, the default is development. As in the config file above we only set one environment as production. And the configs will be replaced with environment variables.</p><p>After running migrate, now check the database we will see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*B-R9ViRVMxSBczCl.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*H3IeEF_yIIdo0ygU.png" /></figure><p>In the next step, we start testing some basic methods of the Model: add, update, delete, search</p><p>A small note when continuing the lesson with the current Pet Category example, we need to update the PetCategory Model a bit, instead of column title -&gt; will switch to column name, for compatibility with the database at this time.</p><blockquote><em>Add PetCategory</em></blockquote><pre>import { PetCategory } from &quot;src/pet/models/pet-category.model&quot;;<br>await PetCategory.create({ ...object });</pre><pre>@Controller(&quot;admin/pet-categories&quot;)<br>export class ManagePetCategoryController {<br>   @Post(&quot;create&quot;)<br>   @Render(&quot;pet/admin/manage-pet-category/create&quot;)<br>   @FormDataRequest()<br>   async create(@Body() createPetCategoryDto: CreatePetCategoryDto) {<br>     const data = {<br>       mode: &quot;create&quot;,<br>     };<br>     // validation<br>     const object = plainToInstance(CreatePetCategoryDto, createPetCategoryDto);</pre><pre>     // ...</pre><pre>     // set value and show success message<br>     Reflect.set(data, &quot;values&quot;, object);</pre><pre>     // create PetCategory<br>     const newPetCategory = await PetCategory.create({ ...object });</pre><pre>     Reflect.set(<br>       data,<br>       &quot;success&quot;,<br>       `Pet Category : ${newPetCategory.id} - ${newPetCategory.name} has been created!`<br>     );<br>     // success<br>     return { data };<br>   }<br>}</pre><p>After running <a href="http://localhost:3000/admin/pet-categories/create">http://localhost:3000/admin/pet-categories/create</a> we get the results as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*M1wbsOevzwapKiS3.png" /></figure><p>In addition, Sequelize also supports you to configure so that you can see the details of the sql statements generated by the ORM. Change a bit in the config for the database connection in the app module.</p><pre>SequelizeModule.forRoot({<br>   uri: &#39;mysql://root:123456@localhost/nestjs_tutorial_2023&#39;,<br>   dialect: &#39;mysql&#39;,<br>   models: models,<br>   logging: console.log,<br>}),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-sOEmsPuR0SOsqX4.png" /></figure><blockquote><em>Search PetCategory — list</em></blockquote><pre>@Controller(&#39;admin/pet-categories&#39;)<br>export class ManagePetCategoryController {<br>   @Get(&#39;&#39;)<br>   @Render(&#39;pet/admin/manage-pet-category/list&#39;)<br>   async getList() {<br>     const petCategories = await PetCategory.findAll();<br>     return {<br>       petCategories,<br>     };<br>   }</pre><pre>&lt;%- include(&#39;layouts/admin/header&#39;); %&gt;<br>&lt;section class=&quot;col-12&quot;&gt;<br>   &lt;div class=&quot;card&quot;&gt;<br>     &lt;div class=&quot;card-body&quot;&gt;<br>       &lt;h5 class=&quot;card-title&quot;&gt;List Pet Categories&lt;/h5&gt;<br>       &lt;div class=&quot;table-responsive&quot;&gt;<br>         &lt;table class=&quot;table table-light table-striped&quot;&gt;<br>           &lt;thead&gt;<br>             &lt;tr&gt;<br>               &lt;th scope=&quot;col&quot; style=&quot;width: 360px&quot;&gt;ID&lt;/th&gt;<br>               &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;<br>             &lt;/tr&gt;<br>           &lt;/thead&gt;<br>           &lt;tbody&gt;<br>             &lt;% petCategories.forEach(petCategory =&gt; { %&gt;<br>             &lt;tr class=&quot;&quot;&gt;<br>               &lt;td&gt;&lt;%= petCategory.id %&gt;&lt;/td&gt;<br>               &lt;td&gt;&lt;%= petCategory.name %&gt;&lt;/td&gt;<br>             &lt;/tr&gt;<br>             &lt;% }) %&gt;<br>           &lt;/tbody&gt;<br>         &lt;/table&gt;<br>       &lt;/div&gt;<br>     &lt;/div&gt;<br>   &lt;/div&gt;<br>&lt;/section&gt;<br>&lt;%- include(&#39;layouts/admin/footer&#39;); %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*8uPa2Dao9RodiKzw.png" /></figure><pre>// find all<br>const petCategories = await PetCategory.findAll();<br>// delete<br>await PetCategory.destroy({ where: { id } });<br>// create<br>const newPetCategory = await PetCategory.create({ ...object });<br>// find by primary key<br>const petCategory = await PetCategory.findByPk(id);<br>// update<br>await petCategory.update(object);</pre><p>Update source code of ManagePetCategory controllers and views</p><pre>import {<br>  Body,<br>  Controller,<br>  Delete,<br>  Get,<br>  Param,<br>  Post,<br>  Redirect,<br>  Render,<br>} from &#39;@nestjs/common&#39;;<br>import { CreatePetCategoryDto } from &#39;src/pet/dtos/pet-dto&#39;;<br>import { plainToInstance } from &#39;class-transformer&#39;;<br>import { validate, ValidationError } from &#39;class-validator&#39;;<br>import { FormDataRequest } from &#39;nestjs-form-data&#39;;<br>import { PetCategory } from &#39;src/pet/models/pet-category.model&#39;;<br>import { Response } from &#39;express&#39;;</pre><pre>const transformError = (error: ValidationError) =&gt; {<br>  const { property, constraints } = error;<br>  return {<br>    property,<br>    constraints,<br>  };<br>};<br>@Controller(&#39;admin/pet-categories&#39;)<br>export class ManagePetCategoryController {<br>  @Get(&#39;&#39;)<br>  @Render(&#39;pet/admin/manage-pet-category/list&#39;)<br>  async getList() {<br>    const petCategories = await PetCategory.findAll();<br>    return {<br>      petCategories,<br>    };<br>  }</pre><pre>  @Post(&#39;delete/:id&#39;)<br>  @Redirect(&#39;/admin/pet-categories/&#39;)<br>  async deleteOne(@Param() { id }: { id: string }) {<br>    await PetCategory.destroy({ where: { id } });<br>  }</pre><pre>  @Get(&#39;create&#39;)<br>  @Render(&#39;pet/admin/manage-pet-category/create&#39;)<br>  view_create() {<br>    // a form<br>    return {<br>      data: {<br>        mode: &#39;create&#39;,<br>      },<br>    };<br>  }</pre><pre>  @Post(&#39;create&#39;)<br>  @Render(&#39;pet/admin/manage-pet-category/create&#39;)<br>  @FormDataRequest()<br>  async create(@Body() createPetCategoryDto: CreatePetCategoryDto) {<br>    const data = {<br>      mode: &#39;create&#39;,<br>    };<br>    // validation<br>    const object = plainToInstance(CreatePetCategoryDto, createPetCategoryDto);<br>    const errors = await validate(object, {<br>      stopAtFirstError: true,<br>    });<br>    if (errors.length &gt; 0) {<br>      Reflect.set(data, &#39;error&#39;, &#39;Please correct all fields!&#39;);<br>      const responseError = {};<br>      errors.map((error) =&gt; {<br>        const rawError = transformError(error);<br>        Reflect.set(<br>          responseError,<br>          rawError.property,<br>          Object.values(rawError.constraints)[0],<br>        );<br>      });<br>      Reflect.set(data, &#39;errors&#39;, responseError);<br>      return { data };<br>    }<br>    // set value and show success message<br>    Reflect.set(data, &#39;values&#39;, object);</pre><pre>    // create PetCategory<br>    const newPetCategory = await PetCategory.create({ ...object });</pre><pre>    Reflect.set(<br>      data,<br>      &#39;success&#39;,<br>      `Pet Category : ${newPetCategory.id} - ${newPetCategory.name} has been created!`,<br>    );<br>    // success<br>    return { data };<br>  }</pre><pre>  @Get(&#39;:id&#39;)<br>  @Render(&#39;pet/admin/manage-pet-category/create&#39;)<br>  async getDetail(@Param() { id }: { id: string }) {<br>    const data = {<br>      mode: &#39;edit&#39;,<br>    };<br>    const petCategory = await PetCategory.findByPk(id);<br>    Reflect.set(data, &#39;values&#39;, petCategory);<br>    return { data };<br>  }</pre><pre>  @Post(&#39;:id&#39;)<br>  @Render(&#39;pet/admin/manage-pet-category/create&#39;)<br>  @FormDataRequest()<br>  async updateOne(<br>    @Param() { id }: { id: string },<br>    @Body() createPetCategoryDto: CreatePetCategoryDto,<br>  ) {<br>    const data = {<br>      mode: &#39;edit&#39;,<br>    };<br>    const petCategory = await PetCategory.findByPk(id);<br>    // validation<br>    const object = plainToInstance(CreatePetCategoryDto, createPetCategoryDto);<br>    const errors = await validate(object, {<br>      stopAtFirstError: true,<br>    });<br>    if (errors.length &gt; 0) {<br>      Reflect.set(data, &#39;error&#39;, &#39;Please correct all fields!&#39;);<br>      const responseError = {};<br>      errors.map((error) =&gt; {<br>        const rawError = transformError(error);<br>        Reflect.set(<br>          responseError,<br>          rawError.property,<br>          Object.values(rawError.constraints)[0],<br>        );<br>      });<br>      Reflect.set(data, &#39;errors&#39;, responseError);<br>      return { data };<br>    }<br>    // set value and show success message<br>    await petCategory.update(object);</pre><pre>    Reflect.set(data, &#39;values&#39;, petCategory);<br>    return { data };<br>  }<br>}</pre><blockquote><em>Views — list.html</em></blockquote><pre>&lt;%- include(&#39;layouts/admin/header&#39;); %&gt;<br>&lt;section class=&quot;col-12&quot;&gt;<br>  &lt;div class=&quot;card&quot;&gt;<br>    &lt;div class=&quot;card-body&quot;&gt;<br>      &lt;h5 class=&quot;card-title&quot;&gt;List Pet Categories&lt;/h5&gt;<br>      &lt;div class=&quot;pb-4&quot;&gt;<br>        &lt;a<br>          class=&quot;btn btn-primary&quot;<br>          href=&quot;/admin/pet-categories/create&quot;<br>          role=&quot;button&quot;<br>          &gt;New Pet Category&lt;/a<br>        &gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;table-responsive&quot;&gt;<br>        &lt;table class=&quot;table table-light table-striped&quot;&gt;<br>          &lt;thead&gt;<br>            &lt;tr&gt;<br>              &lt;th scope=&quot;col&quot; style=&quot;width: 360px&quot;&gt;ID&lt;/th&gt;<br>              &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;<br>              &lt;th scope=&quot;col&quot;&gt;Action&lt;/th&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          &lt;tbody&gt;<br>            &lt;% petCategories.forEach(petCategory =&gt; { %&gt;<br>            &lt;tr class=&quot;&quot;&gt;<br>              &lt;td&gt;&lt;%= petCategory.id %&gt;&lt;/td&gt;<br>              &lt;td&gt;&lt;%= petCategory.name %&gt;&lt;/td&gt;<br>              &lt;td&gt;<br>                &lt;a<br>                  href=&quot;/admin/pet-categories/&lt;%= petCategory.id %&gt;&quot;<br>                  title=&quot;Edit&quot;<br>                  &gt;Edit&lt;/a<br>                &gt;<br>                &lt;form<br>                  action=&quot;/admin/pet-categories/delete/&lt;%= petCategory.id %&gt;&quot;<br>                  method=&quot;post&quot;<br>                &gt;<br>                  &lt;button type=&quot;submit&quot;&gt;Delete&lt;/button&gt;<br>                &lt;/form&gt;<br>              &lt;/td&gt;<br>            &lt;/tr&gt;<br>            &lt;% }) %&gt;<br>          &lt;/tbody&gt;<br>        &lt;/table&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/section&gt;<br>&lt;%- include(&#39;layouts/admin/footer&#39;); %&gt;</pre><blockquote><em>Views — Create/Edit</em></blockquote><pre>&lt;%- include(&#39;layouts/admin/header&#39;); %&gt;<br>&lt;section class=&quot;col-6&quot;&gt;<br>  &lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>    &lt;div class=&quot;card&quot;&gt;<br>      &lt;div class=&quot;card-body&quot;&gt;<br>        &lt;h5 class=&quot;card-title&quot;&gt;<br>          &lt;% if (data.mode === &#39;create&#39;) { %&gt; New Pet Category &lt;% } %&gt; &lt;% if<br>          (data.mode === &#39;edit&#39;) { %&gt; Edit Pet Category &lt;% } %&gt;<br>        &lt;/h5&gt;<br>        &lt;!-- error --&gt;<br>        &lt;% if (data.error){ %&gt;<br>        &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;&lt;%= data.error %&gt;&lt;/div&gt;<br>        &lt;% } %&gt;<br>        &lt;!-- success --&gt;<br>        &lt;% if (data.success){ %&gt;<br>        &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;&lt;%= data.success %&gt;&lt;/div&gt;<br>        &lt;script type=&quot;text/javascript&quot;&gt;<br>          setTimeout(() =&gt; {<br>            window.location.href = &quot;/admin/pet-categories/&quot;;<br>          }, 2000);<br>        &lt;/script&gt;<br>        &lt;% } %&gt;<br>        &lt;div class=&quot;mb-3&quot;&gt;<br>          &lt;label for=&quot;title&quot; class=&quot;form-label&quot;&gt;Name&lt;/label&gt;<br>          &lt;div class=&quot;input-group has-validation&quot;&gt;<br>            &lt;input<br>              type=&quot;text&quot;<br>              class=&quot;form-control &lt;%= data.errors &amp;&amp; data.errors[&#39;name&#39;] ? &#39;is-invalid&#39;: &#39;&#39; %&gt;&quot;<br>              id=&quot;name&quot;<br>              name=&quot;name&quot;<br>              value=&quot;&lt;%= data.values &amp;&amp; data.values[&#39;name&#39;] %&gt;&quot;<br>              placeholder=&quot;Pet Category name&quot;<br>            /&gt;<br>            &lt;% if (data.errors &amp;&amp; data.errors[&#39;name&#39;]) { %&gt;<br>            &lt;div id=&quot;validationServerUsernameFeedback&quot; class=&quot;invalid-feedback&quot;&gt;<br>              &lt;%= data.errors[&#39;name&#39;] %&gt;<br>            &lt;/div&gt;<br>            &lt;% } %&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;% if(!data.success) { %&gt;<br>      &lt;div class=&quot;mb-3 col-12 text-center&quot;&gt;<br>        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;% } %&gt;<br>    &lt;/div&gt;<br>  &lt;/form&gt;<br>&lt;/section&gt;<br>&lt;%- include(&#39;layouts/admin/footer&#39;); %&gt;</pre><h3>Generate data seed with sequelize-cli</h3><blockquote><em>Note at this step, if using generate of cli, target directory in sequelize’s config is now dist directory.</em></blockquote><p>Therefore, we need to slightly adjust the config for <strong>.sequelizerc</strong> as follows. A next note, is to remember to edit the extension file for the seeding or migrations file to the ts extension.</p><pre>const path = require(&quot;path&quot;);</pre><pre>const database_dist = process.env.NODE_ENV === &quot;production&quot; ? &quot;dist&quot; : &quot;src&quot;;</pre><pre>module.exports = {<br>   config: path.resolve(`./${database_dist}/database/config/config.js`),<br>   &quot;seeders-path&quot;: path.resolve(`./${database_dist}/database/seeders`),<br>   &quot;migrations-path&quot;: path.resolve(`./${database_dist}/database/migrations`),<br>};</pre><pre># create migration<br>npx sequelize-cli migration:create --name create-pet-category-table --migrations-path ./src/database/migrations<br># create seed<br>npx sequelize-cli seed:generate --name pet-category<br># build<br>npm run build<br># run migration/seeds<br>NODE_ENV=production npx sequelize-cli db:migrate --env production</pre><pre>import { Column, DataType, Model, Table } from &quot;sequelize-typescript&quot;;</pre><pre>export const PetCategoryTableName = &quot;pet_categories&quot;;</pre><pre>@Table({<br>   tableName: PetCategoryTableName,<br>})<br>export class PetCategory extends Model {<br>   @Column({<br>     primaryKey: true,<br>     type: DataType.UUID,<br>     defaultValue: DataType.UUIDV4,<br>   })<br>   id?: string;</pre><pre>   @Column({<br>     type: DataType.STRING(60),<br>     allowNull: false,<br>   })<br>   name: string;<br>}</pre><blockquote><em>src\database\seeders\20230706141027-pet-category.ts</em></blockquote><pre>&quot;use strict&quot;;</pre><pre>import {<br>   PetCategory,<br>   PetCategoryTableName,<br>} from &quot;src/pet/models/pet-category.model&quot;;</pre><pre>/** @type {import(&#39;sequelize-cli&#39;).Migration} */<br>module.exports = {<br>   async up(queryInterface, Sequelize) {<br>     /**<br>      * Add seed commands here.<br>      *<br>      * Example:<br>      * await queryInterface.bulkInsert(&#39;People&#39;, [{<br>      * name: &#39;John Doe&#39;,<br>      * isBetaMember: false<br>      * }], {});<br>      */<br>     await queryInterface.bulkInsert(<br>       PetCategoryTableName,<br>       [<br>         { name: &quot;Dogs&quot; },<br>         { name: &quot;Cats&quot; },<br>         { name: &quot;Pigs&quot; },<br>         { name: &quot;Birds&quot; },<br>         { name: &quot;Others&quot; },<br>       ],<br>       {}<br>     );<br>   },</pre><pre>   async down(queryInterface, Sequelize) {<br>     /**<br>      * Add commands to revert seed here.<br>      *<br>      * Example:<br>      * await queryInterface.bulkDelete(&#39;People&#39;, null, {});<br>      */<br>     await queryInterface.bulkDelete(PetCategoryTableName, null, {});<br>   },<br>};</pre><p>Everything looks fine, however, when running the migrate seed command, you may get the error described here <a href="https://github.com/sequelize/sequelize/issues/13224">here</a></p><pre>Loaded configuration file &quot;dist\database\config\config.js&quot;.<br>Using environment &quot;production&quot;.<br>== 20230706141027-pet-category: migrating =======</pre><pre>ERROR: Field &#39;id&#39; doesn&#39;t have a default value</pre><p>To bypass this issue while sequelize doesn’t have a patch for this bug, at the time of migration, we will have to generate uuid directly, using <a href="https://www.npmjs.com/package/uuid">this</a> package</p><p>Update a bit the seed file src\database\seeders\20230706141027-pet-category.ts</p><pre>&quot;use strict&quot;;</pre><pre>import { PetCategoryTableName } from &quot;src/pet/models/pet-category.model&quot;;</pre><pre>import { v4 as uuidv4 } from &quot;uuid&quot;;</pre><pre>/** @type {import(&#39;sequelize-cli&#39;).Migration} */<br>module.exports = {<br>   async up(queryInterface, Sequelize) {<br>     /**<br>      * Add seed commands here.<br>      *<br>      * Example:<br>      * await queryInterface.bulkInsert(&#39;People&#39;, [{<br>      * name: &#39;John Doe&#39;,<br>      * isBetaMember: false<br>      * }], {});<br>      */<br>     await queryInterface.bulkInsert(<br>       PetCategoryTableName,<br>       [<br>         { id: uuidv4(), name: &quot;Dogs&quot; },<br>         { id: uuidv4(), name: &quot;Cats&quot; },<br>         { id: uuidv4(), name: &quot;Pigs&quot; },<br>         { id: uuidv4(), name: &quot;Birds&quot; },<br>         { id: uuidv4(), name: &quot;Others&quot; },<br>       ],<br>       {}<br>     );<br>   },</pre><pre>   async down(queryInterface, Sequelize) {<br>     /**<br>      * Add commands to revert seed here.<br>      *<br>      * Example:<br>      * await queryInterface.bulkDelete(&#39;People&#39;, null, {});<br>      */<br>     await queryInterface.bulkDelete(PetCategoryTableName, null, {});<br>   },<br>};</pre><pre>$ NODE_ENV=production npx sequelize-cli db:seed:all</pre><pre>Sequelize CLI [Node: 16.19.1, CLI: 6.6.1, ORM: 6.32.1]</pre><pre>Loaded configuration file &quot;dist\database\config\config.js&quot;.<br>Using environment &quot;production&quot;.<br>== 20230706141027-pet-category: migrating =======<br>== 20230706141027-pet-category: migrated (0.155s)</pre><p>And results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*oiE6tuxPX5L9QW6A.png" /></figure><p>Feel free to read the full courses at <a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs-bai-04-model-and-repository-pattern/">NestJS Course Lesson 04 — Model and Repository Pattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bce194925884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Course Lesson 03 — Controllers & Views]]></title>
            <link>https://medium.com/@gmmiso88/nestjs-course-lesson-03-controllers-views-402218ab80f1?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/402218ab80f1</guid>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 13:52:46 GMT</pubDate>
            <atom:updated>2023-07-04T13:52:46.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>NestJS Course Lesson 03 — Controllers &amp; Views</h3><h3>Source Code</h3><ul><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/lession03">Lession 03 Source Code</a></li></ul><h3>Lesson 03</h3><ol><li>Learn about the module in NestJS — the application to build a directory structure for Pet Website</li><li>Learn about EJS and how to create generic layouts</li><li>Working with forms and checking input data</li></ol><h3>Overview</h3><h4>MVC pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*y1iLDFloeKo0HH4J.png" /></figure><p>Above the data flow model from the time the user makes the request until the result is received.</p><ol><li>Step 1: Controller receives data from User (www/form-data, multiplart/form-data, uri segements, query params, headers, …)</li><li>Step 2: Call to Service to request corresponding business processing, input is data from user</li><li>Step 3: Service makes calls to Model to read/write corresponding data</li><li>Step 4: The model reads/writes the corresponding data in the database</li><li>Step 5: The service sends back to the controller the corresponding data that has been read/written/processed</li><li>Step 6: The controller reads the corresponding template for the interface combined with the data received from the service to render the view to the user.</li><li>Step 7: After rendering the corresponding view, the controller sends this result back to the user -&gt; HTML/JSON, …</li></ol><h4>Apply this MVC architecture to the project and divide the project by module</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*u2yM8GqCO9lSa6HH.png" /></figure><h3>Practice</h3><ol><li>Build the Pet module</li></ol><p><strong>1.1. Controllers</strong></p><ul><li>PetController — /pets — /pets/:petId</li><li>ManagePetController /admin/pets/</li><li>ManagePetCategoryController /admin/pet-categories</li><li>ManagePetAttributeController / admin/pet-attributes</li></ul><p><strong>1.2. Services</strong></p><ul><li>PetService</li><li>PetCategoryService</li><li>PetAttributeService</li></ul><p><strong>1.3. Models</strong></p><ul><li>Pet</li><li>PetCategory</li><li>PetAttribute</li></ul><pre># let&#39;s create a pet module<br>nest g module pet<br># let&#39;s create controllers<br>nest g controller pet/controllers/pet --flat<br># for admin pages<br>nest g controller pet/controllers/admin/manage-pet --flat<br>nest g controller pet/controllers/admin/manage-pet-category --flat<br>nest g controller pet/controllers/admin/manage-pet-attribute --flat</pre><p><strong>app.module.ts</strong></p><pre>// src/app.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { ServeStaticModule } from &quot;@nestjs/serve-static&quot;;<br>import { join } from &quot;path&quot;;<br>import { PetModule } from &quot;./pet/pet.module&quot;;</pre><pre>@Module({<br>   imports: [<br>     // public folder<br>     ServeStaticModule.forRoot({<br>       rootPath: join(process.cwd(), &quot;public&quot;),<br>       serveRoot: &quot;/public&quot;,<br>     }),<br>     PetModule,<br>   ],<br>   controllers: [],<br>   providers: [],<br>})<br>export class AppModule {}</pre><p><strong>pet.module.ts</strong></p><pre>// src/pet/pet.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;</pre><pre>@Module({})<br>export class PetModule {}</pre><pre>import { Controller, Get, Param } from &quot;@nestjs/common&quot;;</pre><pre>@Controller(&quot;pets&quot;)<br>export class PetController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;Pet List&quot;;<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: number }) {<br>     return `Pet Detail ${id}`;<br>   }<br>}</pre><p><strong>At this step NestJS provides some syntax to declare handler for each path</strong></p><ul><li><a href="https://docs.nestjs.com/controllers#route-parameters">Reference about routes, params for controllers in NestJS</a></li></ul><p>Now try to run your application again and see what we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*02BH6yE8mnsGnn5-.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*VlZX0bEBk1zgwp0N.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*5ucqpib5bwkE_t_g.png" /></figure><p>For admin</p><pre>import { Controller, Get, Param } from &quot;@nestjs/common&quot;;</pre><pre>@Controller(&quot;admin/pets&quot;)<br>export class ManagePetController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;admin pet list&quot;;<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: string }) {<br>     return `admin pet detail ${id}`;<br>   }<br>}</pre><pre>import { Controller, Get, Param } from &quot;@nestjs/common&quot;;</pre><pre>@Controller(&quot;admin/pet-categories&quot;)<br>export class ManagePetCategoryController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;admin pet categories&quot;;<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: string }) {<br>     return `admin pet category detail ${id}`;<br>   }<br>}</pre><pre>import { Controller, Get, Param } from &quot;@nestjs/common&quot;;</pre><pre>@Controller(&quot;admin/pet-attributes&quot;)<br>export class ManagePetAttributeController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;admin pet attribute list&quot;;<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: string }) {<br>     return `admin pet attribute detail ${id}`;<br>   }<br>}</pre><p><strong>Let’s start with the form to create a pet category</strong></p><ul><li>Integration with bootstrap (<a href="https://getbootstrap.com/docs/5.0/getting-started/download/">https://getbootstrap.com/docs/5.0/getting-started/download/</a>)</li><li>Use ejs partial (separate common parts of the website — header, footer, and reuse in different templates)</li><li>Create routes</li><li>Connect with view</li><li>Get data from the form and process the results (fake data) The view folder structure will look like this:</li></ul><blockquote><em>views\pet\admin\manage-pet-category\create.ejs</em></blockquote><p>So when using it, we just need to point the path to the template file located in the view directory</p><pre>@Render(&quot;pet/admin/manage-pet-category/create&quot;)</pre><p>After using some examples available at bootstrap we can use the template as below:</p><pre>import { Controller, Get, Param, Post, Render } from &quot;@nestjs/common&quot;;</pre><pre>@Controller(&quot;admin/pet-categories&quot;)<br>export class ManagePetCategoryController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;admin pet categories&quot;;<br>   }</pre><pre>   @Get(&quot;create&quot;)<br>   @Post(&quot;create&quot;)<br>   @Render(&quot;pet/admin/manage-pet-category/create&quot;)<br>   create() {<br>     // a form<br>     return {};<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: string }) {<br>     return `admin pet category detail ${id}`;<br>   }<br>}</pre><p>In which the header, footer will contain the shared elements in the template</p><pre>&lt;%- include(&#39;layouts/admin/header&#39;); %&gt;<br>&lt;h1&gt;Manage Pet Category - Create New Pet Category&lt;/h1&gt;<br>&lt;%- include(&#39;layouts/admin/footer&#39;); %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*L0Dw6UtXHKX2B9Nf.png" /></figure><p>You can find all the related source code here:</p><ul><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/lession03/public/assets">Assets</a></li><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/lession03/views/layouts/admin">Layouts</a></li></ul><p>And we have the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*nw0Mj7TATfpD_VcG.png" /></figure><p>Okie and let’s go to the next step, let’s design a form to input and process data for 1 PetCategory</p><p>Notice that we have 3 use cases for the same view create form of admin pet category:</p><ul><li>Create New Pet Category</li><li>Create New Pet Category success/failure</li><li>Edit Pet Category</li><li>Update Pet Categeory success/failure</li></ul><p>Some constraints of this form:</p><ul><li>Pet category only has title</li><li>Pet category title cannot be left blank</li><li>Pet category title cannot be longer than 150 characters</li></ul><pre># to support multipart/form-data<br>npm install nestjs-form-data --save<br># to support data validation and transformation<br>npm install class-transformer reflect-metadata --save</pre><p><strong>To use multiplat/form-data</strong>, we need to import the NestJSFormData module as shown below.<br>By default NestJS is configured to only support json</p><pre>// src/pet/pet.module.ts</pre><pre>import { Module } from &quot;@nestjs/common&quot;;<br>import { PetController } from &quot;./controllers/pet.controller&quot;;<br>import { ManagePetController } from &quot;./controllers/admin/manage-pet.controller&quot;;<br>import { ManagePetCategoryController } from &quot;./controllers/admin/manage-pet-category.controller&quot;;<br>import { ManagePetAttributeController } from &quot;./controllers/admin/manage-pet-attribute.controller&quot;;<br>import { nestjsFormDataModule } from &quot;nestjs-form-data&quot;;<br>@Module({<br>   imports: [NestjsFormDataModule],<br>   controllers: [<br>     PetController,<br>     ManagePetController,<br>     ManagePetCategoryController,<br>     ManagePetAttributeController,<br>   ],<br>})<br>export class PetModule {}</pre><pre>// pet-dto.ts</pre><pre>import { IsNotEmpty, MaxLength } from &quot;class-validator&quot;;</pre><pre>class CreatePetCategoryDto {<br>   @MaxLength(50)<br>   @IsNotEmpty()<br>   title: string;<br>}</pre><pre>export { CreatePetCategoryDto };</pre><pre>import { Body, Controller, Get, Param, Post, Render } from &quot;@nestjs/common&quot;;<br>import { CreatePetCategoryDto } from &quot;src/pet/dtos/pet-dto&quot;;<br>import { plainToInstance } from &quot;class-transformer&quot;;<br>import { validate, ValidationError } from &quot;class-validator&quot;;<br>import { FormDataRequest } from &quot;nestjs-form-data&quot;;</pre><pre>const transformError = (error: ValidationError) =&gt; {<br>   const { property, constraints } = error;<br>   return {<br>     properties,<br>     constraints,<br>   };<br>};<br>@Controller(&quot;admin/pet-categories&quot;)<br>export class ManagePetCategoryController {<br>   @Get(&quot;&quot;)<br>   getList() {<br>     return &quot;admin pet categories&quot;;<br>   }</pre><pre>   @Get(&quot;create&quot;)<br>   @Render(&quot;pet/admin/manage-pet-category/create&quot;)<br>   view_create() {<br>     // a form<br>     return {<br>       data: {<br>         mode: &quot;create&quot;,<br>       },<br>     };<br>   }</pre><pre>   @Post(&quot;create&quot;)<br>   @Render(&quot;pet/admin/manage-pet-category/create&quot;)<br>   @FormDataRequest()<br>   async create(@Body() createPetCategoryDto: CreatePetCategoryDto) {<br>     const data = {<br>       mode: &quot;create&quot;,<br>     };<br>     // validation<br>     const object = plainToInstance(CreatePetCategoryDto, createPetCategoryDto);<br>     const errors = await validate(object, {<br>       stopAtFirstError: true,<br>     });<br>     if (errors.length &gt; 0) {<br>       Reflect.set(data, &quot;error&quot;, &quot;Please correct all fields!&quot;);<br>       const responseError = {};<br>       errors.map((error) =&gt; {<br>         const rawError = transformError(error);<br>         Reflect.set(<br>           responseError,<br>           rawError.property,<br>           Object.values(rawError.constraints)[0]<br>         );<br>       });<br>       Reflect.set(data, &quot;errors&quot;, responseError);<br>       return { data };<br>     }<br>     // set value and show success message<br>     Reflect.set(data, &quot;values&quot;, object);<br>     Reflect.set(<br>       data,<br>       &quot;success&quot;,<br>       `Pet Category : ${object.title} has been created!`<br>     );<br>     // success<br>     return { data };<br>   }</pre><pre>   @Get(&quot;:id&quot;)<br>   getDetail(@Param() { id }: { id: string }) {<br>     return `admin pet category detail ${id}`;<br>   }<br>}</pre><pre>&lt;%- include(&#39;layouts/admin/header&#39;); %&gt;<br>&lt;section class=&quot;col-6&quot;&gt;<br>   &lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>     &lt;div class=&quot;card&quot;&gt;<br>       &lt;div class=&quot;card-body&quot;&gt;<br>         &lt;h5 class=&quot;card-title&quot;&gt;<br>           &lt;% if (data.mode === &#39;create&#39;) { %&gt; New Pet Category &lt;% } %&gt;<br>         &lt;/h5&gt;<br>         &lt;!-- error --&gt;<br>         &lt;% if (data.error){ %&gt;<br>         &lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;&lt;%= data.error %&gt;&lt;/div&gt;<br>         &lt;% } %&gt;<br>         &lt;!-- success --&gt;<br>         &lt;% if (data.success){ %&gt;<br>         &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;&lt;%= data.success %&gt;&lt;/div&gt;<br>         &lt;% } %&gt;<br>         &lt;div class=&quot;mb-3&quot;&gt;<br>           &lt;label for=&quot;title&quot; class=&quot;form-label&quot;&gt;Title&lt;/label&gt;<br>           &lt;div class=&quot;input-group has-validation&quot;&gt;<br>             &lt;input<br>               type=&quot;text&quot;<br>               class=&quot;form-control &lt;%= data.errors &amp;&amp; data.errors[&#39;title&#39;] ? &#39;is-invalid&#39;: &#39;&#39; %&gt;&quot;<br>               id=&quot;title&quot;<br>               name=&quot;title&quot;<br>               value=&quot;&lt;%= data.values &amp;&amp; data.values[&#39;title&#39;] %&gt;&quot;<br>               placeholder=&quot;Pet Category Title&quot;<br>             /&gt;<br>             &lt;% if (data.errors &amp;&amp; data.errors[&#39;title&#39;]) { %&gt;<br>             &lt;div id=&quot;validationServerUsernameFeedback&quot; class=&quot;invalid-feedback&quot;&gt;<br>               &lt;%= data.errors[&#39;title&#39;] %&gt;<br>             &lt;/div&gt;<br>             &lt;% } %&gt;<br>           &lt;/div&gt;<br>         &lt;/div&gt;<br>       &lt;/div&gt;<br>       &lt;% if(!data.success) { %&gt;<br>       &lt;div class=&quot;mb-3 col-12 text-center&quot;&gt;<br>         &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;<br>       &lt;/div&gt;<br>       &lt;% } %&gt;<br>     &lt;/div&gt;<br>   &lt;/form&gt;<br>&lt;/section&gt;<br>&lt;%- include(&#39;layouts/admin/footer&#39;); %&gt;</pre><p>And we get 3 states of the form as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PwnXgHTzpoGv7Dy8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LjNu9fYQeqKkvJkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*IErQV258YSlPMd7x.png" /></figure><p>Feel free to read the full courses at <a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs-bai03/">NestJS Course Lesson 03 — Controllers &amp; Views</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402218ab80f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nestjs Course — Lesson 02 — Introduction to the MVC pattern]]></title>
            <link>https://medium.com/@gmmiso88/nestjs-course-lesson-02-introduction-to-the-mvc-pattern-17f6cd91e75c?source=rss-80f696e2f101------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f6cd91e75c</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[misostack]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 12:58:07 GMT</pubDate>
            <atom:updated>2023-07-02T12:58:07.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nestjs Course — Lesson 02 — Introduction to the MVC pattern</h3><h3>Source Code</h3><ul><li><a href="https://github.com/misostack/nestjs-tutorial-2023/tree/day02">Session 002 Source Code</a></li></ul><h3>Lesson 02</h3><ol><li>Preliminary design requirements analysis</li><li>Setting up the project structure</li><li>Overview of classes in the MVC model and code practice</li></ol><h3>Request parsing</h3><h4>Sitemap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*jI1BZ1wAz3JI_ghS.png" /></figure><h4>Functional details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*ezP9ri55_nh2u5zX.png" /></figure><h4>Database Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-zVi1OYFXzFkKUWX.png" /></figure><h3>Set up project structure</h3><ol><li>Create a new project with NestJS</li><li>Project folder structure according to module structure and MVC model</li><li>Debug NestJS project with VSCode</li></ol><h4>Create a new project with NestJS</h4><pre>nest new nestjs-tutorial-2023 --skip-install<br>cd nestjs-tutorial-2023<br>npm i</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zlioFJPE_ABzSBgp.png" /></figure><p>After initializing the project, the project’s directory tree structure will look like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*C2Nz5tqFW0LCau8h.png" /></figure><h4>Project directory structure according to the module structure and MVC model</h4><ol><li>Install NestJS to support template Engine EJS</li></ol><p>Let’s go back a bit with the architecture of expressjs, you need to set some parameters as follows:</p><ul><li>Template Engine: some popular template engines like pug, ejs, hbs</li><li>Static Assets: folder containing static files such as css, js, images of the website</li></ul><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const port = process.env.PORT || 1337;<br>const path = require(&quot;path&quot;);</pre><pre>// static assets<br>const publicAssetsPath = path.resolve(process.cwd(), &quot;public&quot;);<br>// using express static middleware<br>app.use(&quot;/public&quot;, express.static(publicAssetsPath));<br>// Your asset will be placed at : <a href="http://localhost:1337/public/assets/main.css">http://localhost:1337/public/assets/main.css</a></pre><pre>// select view engine is ejs<br>app.set(&quot;view engine&quot;, &quot;ejs&quot;);</pre><pre>// set view folder<br>const viewsPath = process.cwd() + &quot;/views&quot;;<br>app.set(&quot;views&quot;, [viewsPath]);</pre><pre>// global variable through app<br>app.locals = {<br>   title: &quot;MVC Tutorial&quot;,<br>};</pre><pre>// home page<br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>   res.render(&quot;index&quot;, { heading: &quot;Home page&quot; });<br>});</pre><pre>app.listen(port, () =&gt; {<br>   console.log(`Example app listening at <a href="http://localhost:${port}`);">http://localhost:${port}`);</a><br>});</pre><p>And in NestJS, how will we do it?</p><pre>npm install --save @nestjs/serve-static<br>npm i --save ejs</pre><pre>// src/app.module.ts<br>import { Module } from &quot;@nestjs/common&quot;;<br>import { AppController } from &quot;./app.controller&quot;;<br>import { AppService } from &quot;./app.service&quot;;<br>import { ServeStaticModule } from &quot;@nestjs/serve-static&quot;;<br>import { join } from &quot;path&quot;;</pre><pre>@Module({<br>   imports: [<br>     // public folder<br>     ServeStaticModule.forRoot({<br>       rootPath: join(process.cwd(), &quot;public&quot;),<br>       // Your asset will be placed at : <a href="http://localhost:1337/public/assets/main.css">http://localhost:1337/public/assets/main.css</a><br>       serveRoot: &quot;/public&quot;,<br>     }),<br>   ],<br>   controllers: [AppController],<br>   providers: [AppService],<br>})<br>export class AppModule {}</pre><pre>// src/main.ts<br>import { NestFactory } from &quot;@nestjs/core&quot;;<br>import { AppModule } from &quot;./app.module&quot;;<br>import { NestExpressApplication } from &quot;@nestjs/platform-express&quot;;<br>import { join } from &quot;path&quot;;</pre><pre>async function bootstrap() {<br>   const app = await NestFactory.create&lt;NestExpressApplication&gt;(AppModule);</pre><pre>   // app.useStaticAssets(join(process.cwd(), &#39;public&#39;));<br>   app.setViewEngine(&quot;ejs&quot;);<br>   app.setBaseViewsDir([join(process.cwd(), &quot;views&quot;)]);</pre><pre>   await app.listen(3000);<br>}<br>bootstrap();</pre><pre>// src/app.controller.ts</pre><pre>import { Controller, Get, Render } from &quot;@nestjs/common&quot;;<br>import { AppService } from &quot;./app.service&quot;;</pre><pre>@Controller()<br>export class AppController {<br>   constructor(private readonly appService: AppService) {}</pre><pre>   @Get()<br>   @Render(&quot;index&quot;)<br>   homePage() {<br>     return {};<br>   }<br>}</pre><blockquote><em>views/index.ejs</em></blockquote><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>   &lt;head&gt;<br>     &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>     &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>     &lt;title&gt;&lt;%= title %&gt;&lt;/title&gt;<br>     &lt;link rel=&quot;stylesheet&quot; href=&quot;/public/assets/main.css&quot; /&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>     &lt;h1&gt;&lt;%= title %&gt;&lt;/h1&gt;<br>     &lt;img<br>       src=&quot;/public/assets/nestjs-tutorial-2023.png&quot;<br>       alt=&quot;NestJS Tutorial 2023&quot;<br>     /&gt;<br>     &lt;script src=&quot;/public/assets/main.js&quot;&gt;&lt;/script&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And here is what you get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*iGCep-iqY-eRHpgz.png" /></figure><h3>References</h3><ul><li>Feel free to find out more details at <a href="https://nextjsvietnam.com/post/khoa-hoc-nestjs-bai-02/">Nestjs Course — Lesson 02 — Introduction to the MVC pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f6cd91e75c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>