<?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 Mitchell Anton on Medium]]></title>
        <description><![CDATA[Stories by Mitchell Anton on Medium]]></description>
        <link>https://medium.com/@mitchella0100?source=rss-8de02baa63ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_v6aPrOTTU4C0XSi</url>
            <title>Stories by Mitchell Anton on Medium</title>
            <link>https://medium.com/@mitchella0100?source=rss-8de02baa63ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:04:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mitchella0100/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[Implementing the Repository Pattern in NestJS (and why we should)]]></title>
            <link>https://medium.com/@mitchella0100/implementing-the-repository-pattern-in-nestjs-and-why-we-should-e32861df5457?source=rss-8de02baa63ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32861df5457</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Mitchell Anton]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 12:02:09 GMT</pubDate>
            <atom:updated>2025-02-16T14:10:45.239Z</atom:updated>
            <content:encoded><![CDATA[<p>The repository pattern is a pattern we can implement in NestJS to ensure that we are not tightly coupled to the ORM, ensuring that it can easily be switched.</p><p>In this article, I will go through why we should implement the repository pattern with an example where we turn our NestJS application from a naive approach with direct injection of repositories into our services, to an approach using the repository pattern.</p><p>Our example will be a simple app where users can create posts, akin to Facebook or Reddit. We will use TypeORM in this example.</p><h3>Database Setup</h3><p>We will have 3 tables to facilitate our app:</p><ul><li>user</li><li>post</li><li>comment</li></ul><pre>// base.entity.ts<br>// Imports...<br><br>export abstract class BaseEntity {<br>    @PrimaryGeneratedColumn()<br>    id: number;<br><br>    @CreateDateColumn({ type: &#39;timestamp&#39;, default: () =&gt; &#39;CURRENT_TIMESTAMP&#39; })<br>    createdAt: Date;<br><br>    @UpdateDateColumn({ type: &#39;timestamp&#39;, default: () =&gt; &#39;CURRENT_TIMESTAMP&#39;, onUpdate: &#39;CURRENT_TIMESTAMP&#39; })<br>    updatedAt: Date;<br>}</pre><pre>// user.entity.ts<br>// Imports...<br><br>@Entity()<br>export class User extends BaseEntity {<br>    @Column({ type: &#39;varchar&#39;, length: 255, nullable: true, unique: true })<br>    email: string;<br><br>    @Column({ type: &#39;varchar&#39;, length: 255 })<br>    password: string;<br><br>    @OneToMany(() =&gt; Post, post =&gt; post.user)<br>    posts: Post[];<br><br>    @OneToMany(() =&gt; Comment, comment =&gt; comment.user)<br>    comments: Comment[];<br>}</pre><pre>// post.entity.ts<br>// Imports...<br><br>@Entity()<br>export class Post extends BaseEntity {<br>    @Column({ type: &#39;varchar&#39;, length: 255 }<br>    title: string;<br><br>    @Column({ type: &#39;text&#39; })<br>    content: string;<br><br>    @OneToMany(() =&gt; Comment, comment =&gt; comment.post)<br>    comments: Comment[];<br><br>    @ManyToOne(() =&gt; User, user =&gt; user.posts)<br>    @JoinColumn({ name: &#39;userId&#39; })<br>    user: User;<br><br>    @Column({ type: &#39;integer&#39; })<br>    userId: number;<br>}</pre><pre>// comment.entity.ts<br>// Imports...<br><br>@Entity()<br>export class Comment extends BaseEntity {<br>    @Column({ type: &#39;text&#39; })<br>    content: string;<br><br>    @ManyToOne(() =&gt; Post, post =&gt; post.comments)<br>    @JoinColumn({ name: &#39;postId&#39; })<br>    post: Post;<br><br>    @Column({ type: &#39;integer&#39; })<br>    postId: number;<br><br>    @ManyToOne(() =&gt; User, user =&gt; user.posts)<br>    @JoinColumn({ name: &#39;userId&#39; })<br>    user: User;<br>}</pre><h3>The Naive Approach</h3><p>Now, suppose we have the following feature in our application:</p><ul><li>User clicks on post to view post and comments.</li></ul><p>This is what the posts module would look like:</p><pre>// posts.module.ts<br>// Imports...<br><br>@Module({<br>    providers: [PostsService, TypeOrmModule.forFeature([Post])],<br>    controllers: [PostsController]<br>})<br>export class PostsModule {}</pre><pre>// posts.controller.ts<br>// Imports...<br><br>@Controller(&#39;posts&#39;)<br>export class PostsController {<br>    constructor(private readonly postsService: PostsService) {}<br><br>    @Post(&#39;:id&#39;)<br>    async viewPost(@Param(&#39;id&#39;, ParseIntPipe) postId: number): Promise&lt;PostDto&gt; {<br>        return this.postsService.viewPostById(postId);<br>    }<br>}</pre><pre>// posts.service.ts<br>// Imports...<br><br>@Injectable()<br>export class PostsService {<br>    constructor(@InjectRepository(Post) private readonly postRepository: Repository&lt;Post&gt;) {}<br><br>    async viewPostById(postId: number): Promise&lt;PostDto&gt; {<br>        return this.postRepository.findOneOrFail({<br>            where: { id: postId },<br>            relations: {<br>                comments: true<br>            }<br>        });<br>    }<br>}</pre><p>This is functional but as the application grows, it is very likely that we will have to execute this same query in multiple places. This introduces the following problems:</p><ol><li>Code Duplication — Writing the same query in multiple places is an example of code duplication, which violates DRY (Do Not Repeat Yourself).</li><li>Tight Coupling with ORM — Writing the same query in multiple places introduces tight coupling to the ORM of our choice. This is because if we were to change the ORM, we may have to change the same query in multiple instances.</li></ol><h3>The Solution — The Repository Pattern</h3><p>Let’s implement the solution to the above problem — the repository pattern!</p><p>Instead of directly injecting the TypeORM repository into our service, we wrap it with our own service. For example:</p><pre>// base.repository.ts<br>// Imports...<br><br>export abstract class BaseRepository {<br>    constructor(private readonly dataSource: DataSource) {}<br><br>    // We do this so we have the ability to run queries inside transactions.<br>    private getEntityManager(entityManager?: EntityManager): EntityManager {<br>        if (entityManager) {<br>            return entityManager;<br>        }<br><br>        return this.dataSource.manager;<br>    }<br><br>    // Pass entityManager to run queries inside transactions.<br>    protected getRepository&lt;T extends ObjectLiteral&gt;(<br>        entityTarget: EntityTarget&lt;T&gt;,<br>        entityManager?: EntityManager,<br>    ): Repository&lt;T&gt; {<br>        const resolvedEntityManager = this.getEntityManager(entityManager);<br>        return resolvedEntityManager.getRepository(entityTarget);<br>    }<br>}</pre><pre>// post.repository.ts<br>// Imports...<br><br>@Injectable()<br>export class PostRepository extends BaseRepository {<br>    private postRepository(entityManager?: EntityManager): Repository&lt;Post&gt; {<br>        return this.getRepository(Post, entityManager);<br>    }<br><br>    async findPostByIdWithCommentsOrFail(postId: number): Promise&lt;Post&gt; {<br>        return this.postRepository().findOneOrFail({<br>            where: { id: postId },<br>            relations: {<br>                comments: true<br>            }<br>        })<br>    }<br>}</pre><p>And our posts service and module becomes:</p><pre>// posts.module.ts<br>// Imports...<br><br>@Module({<br>    // Change provider from TypeOrmModule.forFeature... to PostRepository<br>    providers: [PostsService, PostRepository],<br>    controllers: [PostsController]<br>})<br>export class PostsModule {}</pre><pre>// posts.service.ts<br>// Imports...<br><br>@Injectable()<br>export class PostsService {<br>    constructor(private readonly postRepository: PostRepository) {}<br><br>    async viewPostById(postId: number): Promise&lt;PostDto&gt; {<br>        return this.postRepository.findPostByIdWithCommentsOrFail(postId);<br>    }<br>}</pre><p>Now, if we ever wanted to change the ORM we use, we would only need to change the queries inside post.repository.ts .</p><p>We are almost there, but we are missing one more thing — making the repository implement an interface (well actually, an abstract class since we are using TypeScript — NestJS cannot use an interface for dependency injection since it disappears at runtime).</p><h3>Introducing Interfaces</h3><p>In the previous example, PostRepository does not implement any interface. So instead of doing something constructor(private readonly postRepository: IPostRepository) {} , we currently do constructor(private readonly postRepository: PostRepository) {} .</p><p>If we do not do the former, then the developer must know the implementation details of post.repository.ts to know which methods it exposes. But the whole point of the repository pattern is to abstract this away. We simply want a contract stating that this repository exposes the following methods.</p><p>To achieve this in NestJS, we do not use interfaces, but instead abstract classes. Let’s start by creating two new files, the interface file and the provider file:</p><pre>// post-repository.interface.ts<br>// Imports...<br><br>export abstract class IPostRepository {<br>    abstract findPostByIdWithCommentsOrFail(postId: number): Promise&lt;Post&gt;;<br>}</pre><pre>// post-repository.provider.ts<br>// Imports..<br><br>export const postRepositoryProvider: Provider = {<br>    provide: IPostRepository,<br>    useClass: PostRepository,<br>};</pre><p>And then we modify our PostRepository to implement this “interface” (which is really an abstract class):</p><pre>// post.repository.ts<br>// Imports...<br><br>@Injectable()<br>// Implement IPostRepository<br>export class PostRepository extends BaseRepository implements IPostRepository {<br>    private postRepository(entityManager?: EntityManager): Repository&lt;Post&gt; {<br>        return this.getRepository(Post, entityManager);<br>    }<br><br>    async findPostByIdWithCommentsOrFail(postId: number): Promise&lt;Post&gt; {<br>        return this.postRepository().findOneOrFail({<br>            where: { id: postId },<br>            relations: {<br>                comments: true<br>            }<br>        })<br>    }<br>}</pre><p>And finally, we modify our posts module:</p><pre>// posts.service.ts<br>// Imports...<br><br>@Injectable()<br>export class PostsService {<br>    // postRepository is now of type IPostRepository<br>    constructor(private readonly postRepository: IPostRepository) {}<br><br>    async viewPostById(postId: number): Promise&lt;PostDto&gt; {<br>        return this.postRepository.findPostByIdWithCommentsOrFail(postId);<br>    }<br>}</pre><pre>// posts.module.ts<br>// Imports...<br><br>@Module({<br>    // We now use the postsRepositoryProvider.<br>    providers: [PostsService, postsRepositoryProvider],<br>    controllers: [PostsController]<br>})<br>export class PostsModule {}</pre><p>As you can see above, now a developer can simply visit IPostRepository to see which methods are available, without bothering with implementation details.</p><p>And with this, we are done!</p><h3>Extra Credit — Implementing Transactions</h3><p>You may have noticed above that we have a parameter that keeps appearing in our repositories — entityManager . This is present so that we have the option to run queries in a transaction.</p><p>To do this in a service, see the example below:</p><pre>// posts.service.ts<br>// Imports...<br><br>@Injectable()<br>export class PostsService {<br>    constructor(<br>        private readonly postRepository: IPostRepository,<br>        private readonly notificationRepository: INotificationRepository,<br>        private readonly dataSource: DataSource<br>    ) {}<br><br>    async createPost(payload: CreatePostBodyDto): Promise&lt;PostDto&gt; {<br>        const queryRunner = this.dataSource.createQueryRunner();<br>        await queryRunner.startTransaction();<br><br>        try {<br>            // Pass the entity manager into repository methods so that we run<br>            // these queries inside a transaction.<br>            const post = await this.postRepository.create(payload, queryRunner.manager);<br>            await this.notificationRepository.create(payload.postId, queryRunner.manager);<br><br>            await queryRunner.commitTransaction();<br>            return post;<br>        } catch (error) {<br>            await queryRunner.rollbackTransaction();<br>            throw error;<br>        } finally {<br>            await queryRunner.release();<br>        }<br>    }<br>}</pre><p>And as an example, our post repository would look something like below:</p><pre>// post.repository.ts<br>// Imports...<br><br>@Injectable()<br>export class PostRepository extends BaseRepository implements IPostRepository {<br>    private postRepository(entityManager?: EntityManager): Repository&lt;Post&gt; {<br>        return this.getRepository(Post, entityManager);<br>    }<br><br>    async findPostByIdWithCommentsOrFail(postId: number): Promise&lt;Post&gt; {<br>        return this.postRepository().findOneOrFail({<br>            where: { id: postId },<br>            relations: {<br>                comments: true<br>            }<br>        })<br>    }<br><br>    // New method. Of course, we would also have to update IPostRepository<br>    // to have this new method.<br>    async create(payload: CreatePostPayload, entityManager?: EntityManager): Promise&lt;Post&gt; {<br>        // We pass the entity manager into getRepository to ensure that we <br>        // we run the query in the same context as the transaction.<br>        return this.postRepository(entityManager).save(payload);<br>    }<br>}</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32861df5457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Recursion in Programming]]></title>
            <link>https://medium.com/@mitchella0100/demystifying-recursion-in-programming-03d807db087d?source=rss-8de02baa63ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d807db087d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Mitchell Anton]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 15:20:20 GMT</pubDate>
            <atom:updated>2024-12-27T15:21:25.325Z</atom:updated>
            <content:encoded><![CDATA[<p>As a beginner programmer, recursion is one of the more difficult concepts to learn. The concept of calling a function inside itself is quite confusing.</p><p>In this article, I am to demystify recursion, so that you can start using it in your code.</p><h3>Motivating Example</h3><p>Suppose you want to calculate the nth number of the famous Fibonacci sequence. This is quite simple. The nth Fibonacci number is simply the sum of the (n — 1)th Fibonacci number and the (n — 2)th Fibonacci number. Or in mathematical notation:</p><p>fₙ = fₙ₋₁ + fₙ₋₂</p><p>So, say we want to calculate the 5th fibonacci number. We get:</p><p>f₅ = f₄ + f₃</p><p>But f₄ = f₃ + f₂, and f₃ = f₂ + f₁.</p><p>So we get f₅ = f₃ + f₂ + f₂ + f₁.</p><p>Again, using the definition of the nth Fibonacci number, we get</p><p>f₃ = f₂ + f₁</p><p>f₂ = f₁ + f₀</p><p>f₁ = f₀ + f₋₁</p><p>Substituting, we get:</p><p>f₅ = f₂ + f₁ + f₁ + f₀ + f₀ + f₋₁.</p><p>As you can see, this keeps going forever. Something is not quite right here. This leads us to the second important piece of recursion: the base case.</p><h3>The Base Case</h3><p>Without a “base case”, we end up with an example like the above where the recursion keeps going on forever. You can think of the base case as the <strong>point in time where we stop applying our recurrence relation</strong>.</p><p>In the case of the Fibonacci sequence, we can define our base case for the Fibonacci sequence as f₀ = 1, and f₁ = 1. We also note that since we are talking about the nth Fibonacci number, we can assume that n ≥ 0, since it does not make sense to talk about, for example, the (-2)th Fibonacci number.</p><p>Thus, our formula for th 5th Fibonacci number becomes (using the same expansion as before):</p><p>f₅ = f₄ + f₃</p><p>= f₃ + f₂ + f₂ + f₁</p><p>= f₂ + f₁ + f₁ + f₀ + f₁ + f₀ + f₁</p><p>= f₂ + 1 + 1 + 0 + 1 + 0 + 1</p><p>= f₂ + 4</p><p>= f₁ + f₀ + 4</p><p>= 1 + 0 + 4</p><p>= 5</p><p>And that is it! With a base case, we no longer recurse forever. We have now successfully found the 5th Fibonacci number.</p><p>In summary, our formula for Fibonacci sequence is:</p><p>fₙ = fₙ₋₁ + fₙ₋₂ (n ≥ 2 because for 0 ≤ n ≤ 1, we define the base case).</p><p>f₀ = 0, f₁ = 1 (base case)</p><h3>Time to Write Some Code</h3><p>With our mathematical definition above, it becomes easy to translate into code. We can give fₙ a function signature of fibonacci(n) for better readability. It now becomes apparent how our code should look:</p><pre>def fibonacci(n: int) -&gt; int:<br>  if n &lt; 0:<br>    raise ValueError(&quot;The nth Fibonacci number is only defined for n &gt;= 0.&quot;)<br>  if n == 0:<br>    # Base Case (i.e. f0 = 0 in mathematical notation)<br>    return 0<br>  if n == 1:<br>    # Base Case (i.e. f1 = 1 in mathematical notation)<br>    return 1<br>  return fibonacci(n - 1) + fibonacci(n - 2)</pre><p>The above code is nothing but a python representation of</p><p>fₙ = fₙ₋₁ + fₙ₋₂ (n ≥ 2 because for 0 ≤ n ≤ 1, we define the base case).</p><p>f₀ = 0, f₁ = 1 (base case)</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d807db087d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>