<?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 Aryan aman on Medium]]></title>
        <description><![CDATA[Stories by Aryan aman on Medium]]></description>
        <link>https://medium.com/@aryanaman97?source=rss-3f5f4a93838f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rbhSU_Yz_436XJyP</url>
            <title>Stories by Aryan aman on Medium</title>
            <link>https://medium.com/@aryanaman97?source=rss-3f5f4a93838f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:11:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryanaman97/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[Singleton Design pattern in Go Lang]]></title>
            <link>https://medium.com/@aryanaman97/singleton-design-pattern-in-go-lang-a6a005534658?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a005534658</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[counter-app]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 15:03:45 GMT</pubDate>
            <atom:updated>2025-01-19T15:03:45.315Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Singleton Design Pattern</strong> ensures that a class has only one instance and provides a global point of access to it. When implementing Singleton in Go with <strong>concurrency safety</strong>, you can use synchronization primitives like sync.Once and a <strong>waitover</strong> to ensure that the instance is created only once, even in the presence of multiple goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*XRoAUZESyYPdpxAMpXCazQ.jpeg" /></figure><p>Here’s an example implementation of the Singleton pattern in Go:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br><br>type Singleton struct {<br> data string<br>}<br><br>var (<br> instance *Singleton<br> once     sync.Once<br>)<br><br>// GetInstance returns the single instance of Singleton, ensuring thread safety.<br>func GetInstance() *Singleton {<br> once.Do(func() {<br>  instance = &amp;Singleton{data: &quot;This is the Singleton instance&quot;}<br> })<br> return instance<br>}<br><br>func main() {<br> // Simulate concurrency with waitover<br> var wg sync.WaitGroup<br> wg.Add(2)<br><br> go func() {<br>  defer wg.Done()<br>  singleton1 := GetInstance()<br>  fmt.Println(&quot;Singleton 1:&quot;, singleton1.data)<br> }()<br><br> go func() {<br>  defer wg.Done()<br>  singleton2 := GetInstance()<br>  fmt.Println(&quot;Singleton 2:&quot;, singleton2.data)<br> }()<br><br> wg.Wait()</pre><h3>Explanation</h3><ol><li><strong>sync.Once</strong>: The sync.Once ensures that the initialization function (once.Do) is executed exactly <strong>once</strong>, no matter how many goroutines call GetInstance. This is thread-safe and does not require additional locking or manual synchronization.</li><li><strong>Waitover</strong>:</li></ol><ul><li>We use a sync.WaitGroup to simulate multiple goroutines accessing the Singleton instance concurrently.</li><li>The WaitGroup ensures the main function waits until all goroutines complete before exiting.</li></ul><ol><li><strong>Concurrent Safety</strong>: Even if multiple goroutines call GetInstance simultaneously, sync.Once ensures that the Singleton instance is created exactly once.</li></ol><h3>Output</h3><p>When you run the above code, the output might look like this:</p><pre>Singleton 1: This is the Singleton instance<br>Singleton 2: This is the Singleton instance</pre><h3>Advantages</h3><ul><li><strong>Thread-safe</strong>: sync.Once eliminates the need for complex locking mechanisms.</li><li><strong>Efficient</strong>: The initialization code executes only once, even in the presence of multiple goroutines.</li></ul><p>This implementation is both safe and idiomatic in Go.</p><h3><strong>One more Example : Creating a sequence generator (Counter App with Singelton pattern)</strong></h3><p><strong>Singleton Sequence Generator Implementation</strong></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;sync/atomic&quot;<br>)<br><br><br>type SequenceGenerator struct {<br> currentValue int64<br>}<br><br>var (<br> instance *SequenceGenerator<br> once     sync.Once<br>)<br><br>// GetSequenceGenerator returns the singleton instance of the SequenceGenerator.<br>func GetSequenceGenerator() *SequenceGenerator {<br> once.Do(func() {<br>  instance = &amp;SequenceGenerator{currentValue: 0}<br> })<br> return instance<br>}<br><br>// Next generates the next number in the sequence.<br>func (s *SequenceGenerator) Next() int64 {<br> return atomic.AddInt64(&amp;s.currentValue, 1)<br>}<br><br>func main() {<br> // Simulate concurrent access to the Singleton Sequence Generator<br> var wg sync.WaitGroup<br> wg.Add(5)<br><br> for i := 0; i &lt; 5; i++ {<br>  go func(id int) {<br>   defer wg.Done()<br>   gen := GetSequenceGenerator() // Get the singleton instance<br>   fmt.Printf(&quot;Goroutine %d: Next Sequence -&gt; %d\n&quot;, id, gen.Next())<br>  }(i)<br> }<br><br> wg.Wait()<br>}</pre><h3>Key Points of Implementation</h3><ol><li><strong>Singleton Design Pattern</strong>:</li></ol><ul><li>sync.Once ensures the singleton instance (instance) is initialized only once, even when accessed concurrently by multiple goroutines.</li><li>The GetSequenceGenerator function provides the global point of access to the instance.</li></ul><p><strong>2. Thread-Safe Increment</strong>:</p><ul><li>The Next method uses atomic.AddInt64 to increment the sequence safely in a concurrent environment.</li></ul><p><strong>Global Access</strong>:</p><ul><li>The singleton ensures that the same instance of the sequence generator is used throughout the program.</li></ul><p><strong>Concurrent Usage</strong>:</p><ul><li>Multiple goroutines access the GetSequenceGenerator method concurrently, but only one instance of SequenceGenerator is created.</li></ul><h4><strong>OUTPUT:</strong></h4><pre>Goroutine 0: Next Sequence -&gt; 1<br>Goroutine 3: Next Sequence -&gt; 4<br>Goroutine 2: Next Sequence -&gt; 3<br>Goroutine 1: Next Sequence -&gt; 2<br>Goroutine 4: Next Sequence -&gt; 5</pre><h3>Advantages of This Implementation</h3><p><strong>Singleton Pattern</strong>:</p><ul><li>Guarantees only one instance of the sequence generator across the application.</li></ul><p><strong>Thread-Safe</strong>:</p><ul><li>Uses sync.Once for safe singleton creation and atomic operations for sequence generation.</li></ul><p><strong>Easy Integration</strong>:</p><ul><li>The singleton can be accessed globally using GetSequenceGenerator.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a005534658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singelton Design Pattern in NEST js or NODE js]]></title>
            <link>https://medium.com/@aryanaman97/singelton-design-pattern-in-nest-js-or-node-js-a1ded6c0dc99?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ded6c0dc99</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 19:58:29 GMT</pubDate>
            <atom:updated>2024-08-03T20:24:28.995Z</atom:updated>
            <content:encoded><![CDATA[<p>The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance. This pattern is commonly used in scenarios where a single resource, like a configuration object or a connection pool, needs to be shared across the entire application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjKAWxp8JDuTpqcvtxHi2Q.png" /></figure><p>Node js simple example</p><h4>Example</h4><p>Let’s create a singleton class called Config:</p><pre>// config.js<br>class Config {<br>  constructor() {<br>    if (Config.instance == null) {<br>      this.configData = {};<br>      Config.instance = this;<br>    }<br><br>    return Config.instance;<br>  }<br><br>  set(key, value) {<br>    this.configData[key] = value;<br>  }<br><br>  get(key) {<br>    return this.configData[key];<br>  }<br>}<br><br>const instance = new Config();<br>Object.freeze(instance);<br><br>module.exports = instance;</pre><p>Here, Config is a class with a constructor that initializes configData. The Config.instance ensures that only one instance is created. We freeze the instance to prevent modification.</p><p>You can use this singleton class in your application as follows:</p><pre>// app.js<br>const config = require(&#39;./config&#39;);<br><br>config.set(&#39;name&#39;, &#39;MyApp&#39;);<br>console.log(config.get(&#39;name&#39;)); // Outputs: MyApp<br><br>const anotherConfig = require(&#39;./config&#39;);<br>console.log(anotherConfig.get(&#39;name&#39;)); // Outputs: MyApp</pre><p><strong>Node.js: Use the module caching feature and </strong><strong>Object.freeze() to implement singletons.</strong></p><p>In the context of creating singleton instances, especially for resources like database connections, different strategies can be employed to ensure proper instantiation and lifecycle management. Here’s an explanation of eager, lazy, synchronized, and double-checked locking patterns in the context of NestJS, with a focus on database connections.</p><h3>1. Eager Initialization</h3><p><strong>Eager Initialization</strong> is a straight forward way to create a singleton instance. The instance is created as soon as the application starts, regardless of whether it is needed immediately.</p><h4>Example</h4><p>In NestJS, you might use a module to set up a database connection eagerly:</p><pre>import { Module, OnModuleInit } from &#39;@nestjs/common&#39;;<br>import { createConnection, Connection } from &#39;typeorm&#39;;<br><br>@Module({})<br>export class DatabaseModule implements OnModuleInit {<br>  private static connection: Connection;<br><br>  onModuleInit() {<br>    DatabaseModule.connection = createConnection({<br>      type: &#39;mysql&#39;,<br>      host: &#39;localhost&#39;,<br>      port: 3306,<br>      username: &#39;root&#39;,<br>      password: &#39;password&#39;,<br>      database: &#39;test&#39;,<br>    });<br>  }<br><br>  static getConnection(): Connection {<br>    return DatabaseModule.connection;<br>  }<br>}</pre><p>In this example, the database connection is established as soon as the DatabaseModule is initialized. This approach is simple but may be inefficient if the connection is not needed immediately or if it is costly to create.</p><h3>2. Lazy Initialization</h3><p><strong>Lazy Initialization</strong> delays the creation of the singleton instance until it is first needed. This is useful for deferring resource-intensive operations until absolutely necessary.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { createConnection, Connection } from &#39;typeorm&#39;;<br><br>@Injectable()<br>export class DatabaseService {<br>  private static connection: Connection;<br><br>  async getConnection(): Promise&lt;Connection&gt; {<br>    if (!DatabaseService.connection) {<br>      DatabaseService.connection = await createConnection({<br>        type: &#39;mysql&#39;,<br>        host: &#39;localhost&#39;,<br>        port: 3306,<br>        username: &#39;root&#39;,<br>        password: &#39;password&#39;,<br>        database: &#39;test&#39;,<br>      });<br>    }<br>    return DatabaseService.connection;<br>  }<br>}</pre><p>In this case, the DatabaseService only establishes the database connection when getConnection() is called for the first time.</p><h3>3. Synchronized Access</h3><p><strong>Synchronized Access</strong> ensures that only one thread can access the critical section of code at a time. In JavaScript and TypeScript, this concept is managed differently because JavaScript is single-threaded. However, in asynchronous contexts, you can use techniques to prevent race conditions.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { createConnection, Connection } from &#39;typeorm&#39;;<br><br>@Injectable()<br>export class DatabaseService {<br>  private static connection: Connection;<br>  private static connectionPromise: Promise&lt;Connection&gt;;<br><br>  async getConnection(): Promise&lt;Connection&gt; {<br>    if (!DatabaseService.connection) {<br>      if (!DatabaseService.connectionPromise) {<br>        DatabaseService.connectionPromise = createConnection({<br>          type: &#39;mysql&#39;,<br>          host: &#39;localhost&#39;,<br>          port: 3306,<br>          username: &#39;root&#39;,<br>          password: &#39;password&#39;,<br>          database: &#39;test&#39;,<br>        }).then(connection =&gt; {<br>          DatabaseService.connection = connection;<br>          return connection;<br>        });<br>      }<br>      await DatabaseService.connectionPromise;<br>    }<br>    return DatabaseService.connection;<br>  }<br>}</pre><p>In this example, connectionPromise ensures that only one asynchronous operation for creating the connection is in progress at a time, preventing multiple simultaneous connection attempts.</p><h3>4. Double-Checked Locking</h3><p><strong>Double-Checked Locking</strong> reduces the overhead of acquiring a lock by first checking the resource without acquiring the lock, then checking again with the lock if necessary. This pattern is typically used in multi-threaded environments, which is not directly applicable to JavaScript, but a similar effect can be achieved.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { createConnection, Connection } from &#39;typeorm&#39;;<br><br>@Injectable()<br>export class DatabaseService {<br>  private static connection: Connection;<br>  private static connectionPromise: Promise&lt;Connection&gt;;<br><br>  async getConnection(): Promise&lt;Connection&gt; {<br>    if (!DatabaseService.connection) {<br>      if (!DatabaseService.connectionPromise) {<br>        DatabaseService.connectionPromise = createConnection({<br>          type: &#39;mysql&#39;,<br>          host: &#39;localhost&#39;,<br>          port: 3306,<br>          username: &#39;root&#39;,<br>          password: &#39;password&#39;,<br>          database: &#39;test&#39;,<br>        }).then(connection =&gt; {<br>          DatabaseService.connection = connection;<br>          return connection;<br>        });<br>      } else {<br>        await DatabaseService.connectionPromise;<br>      }<br>    }<br>    return DatabaseService.connection;<br>  }<br>}</pre><p>Here, the check if (!DatabaseService.connection) is performed twice—once without waiting for the lock and once with waiting for the asynchronous operation—effectively ensuring that only one connection creation occurs.</p><h3>Key Points in NestJS</h3><ul><li><strong>Dependency Injection (DI)</strong>: NestJS uses DI, and services (providers) are singletons by default. This fits naturally with singleton design patterns.</li><li><strong>Asynchronous Nature</strong>: Given JavaScript’s event-driven nature, handling asynchronous operations correctly (e.g., with Promises) is crucial in singleton patterns, especially for resources like database connections.</li></ul><p>These patterns help manage singleton resources efficiently, ensuring thread safety and optimal resource utilization in applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ded6c0dc99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to play music/audio in your web Apps using Angular]]></title>
            <link>https://medium.com/@aryanaman97/how-to-play-music-audio-in-your-web-apps-using-angular-25a64aabffb7?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a64aabffb7</guid>
            <category><![CDATA[angualr]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[ryan-music-player]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 06:03:33 GMT</pubDate>
            <atom:updated>2024-07-14T08:31:45.863Z</atom:updated>
            <content:encoded><![CDATA[<p>I have created a music-player package for it , let’s start using it, you can use same package in your react based typescript project.</p><p><a href="https://www.npmjs.com/package/ryan-music-player?activeTab=readme">https://www.npmjs.com/package/ryan-music-player?activeTab=readme</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrBp-HEynQYBha6YQcpoGw.png" /></figure><p><strong>Install </strong><strong>ryan-music-player</strong>:</p><p>First, install your library using npm in your existing angular project:</p><pre>npm i ryan-music-player</pre><p><strong>Import and Use </strong><strong>AudioManager in Angular Component</strong>:</p><p>After installing ryan-music-player, you can use AudioManager in any Angular component where you want to manage audio playback.</p><p><strong>Example Component Usage (</strong><strong>app.component.ts)</strong>:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import AudioManager from &quot;ryan-music-player&quot;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit{<br>  audioManager: AudioManager;<br>  volume: number;<br><br>  constructor(){<br>    this.audioManager = new AudioManager([&#39;assets/audio.mp3&#39;,&#39;assets/audio.mp3&#39;]);<br>    this.volume=1;<br>  }<br>  ngOnInit(){<br>  }<br>  playAudio() {<br>    this.audioManager.play();<br>  }<br><br>  pauseAudio() {<br>    this.audioManager.pause();<br>  }<br><br>  stopAudio() {<br>    this.audioManager.stop();<br>  }<br><br>  setVolume(volume:number) {<br>    this.audioManager.setVolume(volume);<br> <br>  }<br>  toggleShuffle() {<br>    this.audioManager.toggleShuffle();<br>  }<br><br>  nextTrack() {<br>    this.audioManager.nextTrack();<br>  }<br><br>  previousTrack() {<br>    this.audioManager.previousTrack();<br>  }<br><br><br>}</pre><p>Here , I am using audio from assets file .</p><h4>Create <strong>typings.d.ts</strong> file inside your<strong> src folder for type check</strong></h4><pre>declare module &#39;ryan-music-player&#39; {<br>  class AudioManager {<br>    constructor(srcs: string[]);<br>    play(): void;<br>    pause(): void;<br>    stop(): void;<br>    seek(time: number): void;<br>    setVolume(volume: number): void;<br>    on(event: string, handler: () =&gt; void): void;<br>    off(event: string, handler: () =&gt; void): void;<br>    getCurrentTime(): number;<br>    getDuration(): number;<br>    toggleShuffle():void<br>    nextTrack():void<br>    previousTrack():void<br><br>  }<br>  export default AudioManager;<br>}</pre><p><strong>HTML Template (</strong><strong>app.component.html)</strong>:</p><p>Use Angular bindings to trigger audio playback controls in your template:</p><pre><br>&lt;div class=&quot;audio-controls&quot;&gt;<br>  &lt;button (click)=&quot;previousTrack()&quot;&gt;Previous&lt;/button&gt;<br>  &lt;button (click)=&quot;playAudio()&quot;&gt;Play&lt;/button&gt;<br>  &lt;button (click)=&quot;pauseAudio()&quot;&gt;Pause&lt;/button&gt;<br>  &lt;button (click)=&quot;stopAudio()&quot;&gt;Stop&lt;/button&gt;<br>  &lt;button (click)=&quot;nextTrack()&quot;&gt;Next&lt;/button&gt;<br>  &lt;button (click)=&quot;toggleShuffle()&quot;&gt;Shuffle&lt;/button&gt;<br>  &lt;input type=&quot;range&quot; min=&quot;0&quot; max=&quot;1&quot; step=&quot;0.1&quot; [(ngModel)]=&quot;volume&quot; (input)=&quot;setVolume(volume)&quot;&gt;<br>&lt;/div&gt;</pre><p><strong>SCSS Template (</strong><strong>app.component.scss)</strong>:</p><pre>.audio-controls {<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    margin-top: 20px;<br>    gap: 10px;<br>  <br>    button {<br>      background-color: #1db954; /* Spotify Green */<br>      border: none;<br>      color: white;<br>      padding: 10px 20px;<br>      text-align: center;<br>      text-decoration: none;<br>      display: inline-block;<br>      font-size: 16px;<br>      cursor: pointer;<br>      border-radius: 50px;<br>      transition: background-color 0.3s ease, transform 0.3s ease;<br>  <br>      &amp;:hover {<br>        background-color: #1ed760;<br>        transform: scale(1.05);<br>      }<br>  <br>      &amp;:focus {<br>        outline: none;<br>        box-shadow: 0 0 10px #1db954;<br>      }<br>    }<br>  <br>    input[type=&quot;range&quot;] {<br>      width: 150px;<br>      -webkit-appearance: none;<br>      appearance: none;<br>      height: 8px;<br>      background: #d3d3d3;<br>      outline: none;<br>      opacity: 0.7;<br>      transition: opacity 0.2s;<br>  <br>      &amp;:hover {<br>        opacity: 1;<br>      }<br>  <br>      &amp;::-webkit-slider-thumb {<br>        -webkit-appearance: none;<br>        appearance: none;<br>        width: 25px;<br>        height: 25px;<br>        background: #1db954;<br>        cursor: pointer;<br>        border-radius: 50%;<br>        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);<br>      }<br>  <br>      &amp;::-moz-range-thumb {<br>        width: 25px;<br>        height: 25px;<br>        background: #1db954;<br>        cursor: pointer;<br>        border-radius: 50%;<br>        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);<br>      }<br>    }<br>  }</pre><p><strong>Additional Integration</strong>:</p><ul><li><strong>Angular Services</strong>: Consider using Angular services to manage state or provide access to AudioManager across multiple components.</li><li><strong>RxJS</strong>: Use RxJS observables for handling audio events and state changes if needed.</li></ul><h3>Running Your Angular Project</h3><p>Once you’ve integrated ryan-music-player into your Angular project:</p><ol><li><strong>Start Angular Development Server</strong>:</li><li>Run your Angular project locally:</li></ol><pre>ng serve</pre><p>This command starts the Angular development server. By default, your application will be available at <a href="http://localhost:4200.">http://localhost:4200.</a></p><p><strong>Access Your Application</strong>:</p><p>Open your web browser and navigate to http://localhost:4200 to view and interact with your Angular application.</p><h3>Summary</h3><p>By following these steps, you can integrate ryan-music-player into your Angular project to manage audio playback effectively. Adjust the paths, UI elements, and functionality as per your project&#39;s requirements and desired user experience. If you have any specific questions or encounter issues during integration, feel free to ask for further assistance!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a64aabffb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS codebase following the SOLID design principles for a Spotify service]]></title>
            <link>https://medium.com/@aryanaman97/nestjs-codebase-following-the-solid-design-principles-for-a-spotify-service-c65702c893d5?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65702c893d5</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[spotify-playlist]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 18:53:11 GMT</pubDate>
            <atom:updated>2024-07-04T18:53:11.346Z</atom:updated>
            <content:encoded><![CDATA[<p>Install NestJS and Initialize the Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4qVPGbuM_C91xa5T.png" /></figure><pre>npm i -g @nestjs/cli<br>nest new spotify-service</pre><p>Set Up Modules, Services, and Controllers</p><pre>nest g module spotify<br>nest g service spotify<br>nest g controller spotify</pre><p>Create interfaces for your service contracts in a new directory, interfaces.</p><pre>export interface ISpotifyService {<br>  getTrack(id: string): Promise&lt;any&gt;;<br>  getPlaylist(id: string): Promise&lt;any&gt;;<br>  search(query: string): Promise&lt;any&gt;;<br>}</pre><p>Implement the service by adhering to the ISpotifyService interface.</p><pre>// src/spotify/spotify.service.ts<br>import { Injectable, HttpService } from &#39;@nestjs/common&#39;;<br>import { ISpotifyService } from &#39;../interfaces/spotify.service.interface&#39;;<br><br>@Injectable()<br>export class SpotifyService implements ISpotifyService {<br>  constructor(private readonly httpService: HttpService) {}<br><br>  async getTrack(id: string): Promise&lt;any&gt; {<br>    const response = await this.httpService.get(`https://api.spotify.com/v1/tracks/${id}`).toPromise();<br>    return response.data;<br>  }<br><br>  async getPlaylist(id: string): Promise&lt;any&gt; {<br>    const response = await this.httpService.get(`https://api.spotify.com/v1/playlists/${id}`).toPromise();<br>    return response.data;<br>  }<br><br>  async search(query: string): Promise&lt;any&gt; {<br>    const response = await this.httpService.get(`https://api.spotify.com/v1/search?q=${query}`).toPromise();<br>    return response.data;<br>  }<br>}</pre><p>Ensure that the service is provided and the HTTP module is imported in the SpotifyModule.</p><pre><br>Copy code<br>// src/spotify/spotify.module.ts<br>import { Module, HttpModule } from &#39;@nestjs/common&#39;;<br>import { SpotifyService } from &#39;./spotify.service&#39;;<br>import { SpotifyController } from &#39;./spotify.controller&#39;;<br><br>@Module({<br>  imports: [HttpModule],<br>  providers: [SpotifyService],<br>  controllers: [SpotifyController]<br>})<br>export class SpotifyModule {}</pre><p>Implement the controller to handle HTTP requests.</p><pre>// src/spotify/spotify.controller.ts<br>import { Controller, Get, Param, Query } from &#39;@nestjs/common&#39;;<br>import { SpotifyService } from &#39;./spotify.service&#39;;<br><br>@Controller(&#39;spotify&#39;)<br>export class SpotifyController {<br>  constructor(private readonly spotifyService: SpotifyService) {}<br><br>  @Get(&#39;track/:id&#39;)<br>  async getTrack(@Param(&#39;id&#39;) id: string) {<br>    return this.spotifyService.getTrack(id);<br>  }<br><br>  @Get(&#39;playlist/:id&#39;)<br>  async getPlaylist(@Param(&#39;id&#39;) id: string) {<br>    return this.spotifyService.getPlaylist(id);<br>  }<br><br>  @Get(&#39;search&#39;)<br>  async search(@Query(&#39;query&#39;) query: string) {<br>    return this.spotifyService.search(query);<br>  }<br>}</pre><p><strong>Apply SOLID Principles</strong></p><ul><li><strong>Single Responsibility Principle (SRP)</strong>: Each service (like SpotifyService) has one responsibility.</li><li><strong>Open/Closed Principle (OCP)</strong>: New functionality can be added by creating new services or extending existing ones without modifying the existing code.</li><li><strong>Liskov Substitution Principle (LSP)</strong>: If you create a subclass of SpotifyService, it should be able to replace the original without altering the correct behavior of the program.</li><li><strong>Interface Segregation Principle (ISP)</strong>: ISpotifyService ensures that clients only need to implement methods they use.</li><li><strong>Dependency Inversion Principle (DIP)</strong>: High-level modules do not depend on low-level modules. Both depend on abstractions (interfaces).</li></ul><p>Import the SpotifyModule into the main application module.</p><pre>// src/app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { SpotifyModule } from &#39;./spotify/spotify.module&#39;;<br><br>@Module({<br>  imports: [SpotifyModule],<br>})<br>export class AppModule {}</pre><p><strong>Running the Application</strong></p><pre>npm run start</pre><p>This structure ensures that your codebase adheres to the SOLID principles, making it easier to maintain, extend, and test.</p><p>Sure! Here’s a representation of what your folder structure might look like for the NestJS Spotify service following the SOLID principles:</p><pre>spotify-service/<br>├── src/<br>│   ├── interfaces/<br>│   │   └── spotify.service.interface.ts<br>│   ├── spotify/<br>│   │   ├── dto/<br>│   │   ├── entities/<br>│   │   ├── spotify.controller.ts<br>│   │   ├── spotify.module.ts<br>│   │   ├── spotify.service.ts<br>│   ├── app.module.ts<br>│   ├── main.ts<br>├── test/<br>├── package.json<br>├── tsconfig.json<br>├── tslint.json</pre><h3>Folder Structure Details</h3><ul><li>interfaces/: Contains interface definitions to ensure the separation of concerns and adherence to the Dependency Inversion Principle.</li><li>spotify.service.interface.ts: Defines the contract for the Spotify service.</li><li>spotify/: Contains the module, service, and controller related to the Spotify functionality.</li><li>dto/: (Optional) Contains Data Transfer Objects (DTOs) to define the structure of data transferred between client and server.</li><li>entities/: (Optional) Contains entities that define the structure of data stored in the database.</li><li>spotify.controller.ts: Handles incoming HTTP requests and returns responses.</li><li>spotify.module.ts: Sets up the module, imports necessary modules, and provides the service.</li><li>spotify.service.ts: Implements the business logic and interacts with external services like the Spotify API.</li><li>app.module.ts: The root module that imports the SpotifyModule.</li><li>main.ts: The entry point of the application.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65702c893d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding WebSockets to Angular projects]]></title>
            <link>https://medium.com/@aryanaman97/adding-websockets-to-angular-projects-21275a999b40?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/21275a999b40</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Fri, 10 May 2024 19:16:24 GMT</pubDate>
            <atom:updated>2024-05-10T19:16:24.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vaqZMzazDDFI-L6Zy4LZkg.png" /></figure><h3>1. Install Required Dependencies:</h3><p>Ensure you have the necessary dependencies installed. Angular uses the rxjs library for handling observables, which is usually included by default. However, you may need to install additional packages for WebSocket functionality.</p><p>npm install — save rxjs @angular/websocket</p><h3>2. Create WebSocket Service:</h3><p>Create a service to handle WebSocket connections. This service will encapsulate the WebSocket logic and provide methods for interacting with the WebSocket.</p><pre>// app.component.ts<br><br>import { Component } from &#39;@angular/core&#39;;<br>import { WebsocketService } from &#39;./websocket.service&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent {<br>  constructor(private websocketService: WebsocketService) {}<br><br>  ngOnInit() {<br>    const wsUrl = &#39;ws://your-websocket-url&#39;;<br>    this.websocketService.connect(wsUrl).subscribe(<br>      msg =&gt; console.log(&#39;Received message:&#39;, msg),<br>      err =&gt; console.error(&#39;Error:&#39;, err),<br>      () =&gt; console.log(&#39;WebSocket connection closed&#39;)<br>    );<br>  }<br><br>  sendMessage() {<br>    const message = { type: &#39;chat&#39;, text: &#39;Hello WebSocket!&#39; };<br>    this.websocketService.send(message);<br>  }<br><br>  ngOnDestroy() {<br>    this.websocketService.close();<br>  }<br>}</pre><h3>3.Use WebSocket Service in Components:</h3><p>Inject the WebSocket service into your Angular components where you want to use WebSocket functionality.</p><pre>// app.component.ts<br><br>import { Component } from &#39;@angular/core&#39;;<br>import { WebsocketService } from &#39;./websocket.service&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br>export class AppComponent {<br>  constructor(private websocketService: WebsocketService) {}<br><br>  ngOnInit() {<br>    const wsUrl = &#39;ws://your-websocket-url&#39;;<br>    this.websocketService.connect(wsUrl).subscribe(<br>      msg =&gt; console.log(&#39;Received message:&#39;, msg),<br>      err =&gt; console.error(&#39;Error:&#39;, err),<br>      () =&gt; console.log(&#39;WebSocket connection closed&#39;)<br>    );<br>  }<br><br>  sendMessage() {<br>    const message = { type: &#39;chat&#39;, text: &#39;Hello WebSocket!&#39; };<br>    this.websocketService.send(message);<br>  }<br><br>  ngOnDestroy() {<br>    this.websocketService.close();<br>  }<br>}</pre><h3>4. Update Angular Module:</h3><p>Add the WebSocket service to the providers array in your Angular module.</p><pre>// app.module.ts<br>// it can be any module , you can use your feature module also , <br>// depend on your projects<br><br><br>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { WebsocketService } from &#39;./websocket.service&#39;;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule<br>  ],<br>  providers: [WebsocketService], // Add WebsocketService to providers<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><h3>5. Handle WebSocket Events:</h3><p>In your component, subscribe to WebSocket messages and handle them appropriately. You can also send messages to the server using the send() method of the WebSocket service.</p><h3>6. Test and Debug:</h3><p>Test your WebSocket implementation thoroughly and debug any issues that arise. Use browser developer tools to inspect WebSocket connections and messages.</p><p>By following these steps, you should be able to add WebSocket functionality to your Angular project and establish real-time communication with a WebSocket server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21275a999b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRUD with elysia.js and Mongodb runtime as BUN(1.0.26)]]></title>
            <link>https://medium.com/@aryanaman97/crud-with-elysia-js-and-mongodb-runtime-as-bun-1-0-26-1584c69c36bc?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1584c69c36bc</guid>
            <category><![CDATA[bűn]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[elysia]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 17:50:36 GMT</pubDate>
            <atom:updated>2024-02-13T18:30:16.143Z</atom:updated>
            <content:encoded><![CDATA[<p>You can install bun from here</p><p><a href="https://bun.sh/docs/installation">Installation | Bun Docs</a></p><p>Benefits of using BUN( below image explains well)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_Bq1yTpjZibOWNNja8Xrw.png" /></figure><p>let’s now start with CODE</p><pre><br>mkdir USER-CRUD<br>cd USER-CRUD<br>bun init</pre><p>Install some packages with BUN.</p><pre>bun install mongoose  <br>bun i elysia <br>bun i @elysiajs/swagger<br></pre><p>Create a folder structure now</p><pre>project-root/<br>├── src/<br>│   ├── controllers/<br>│   │   └── userController.ts<br>│   ├── models/<br>│   │   └── userModel.ts<br>│   ├── routes/<br>│   │   └── userRoutes.ts<br>│   └── index.ts<br>├── package.json<br>└── node_modules/</pre><p>src/: This directory contains all your source code.</p><ul><li>controllers/: Contains controller files for handling business logic.</li><li>models/: Contains Mongoose model files for defining data schema.</li><li>routes/: Contains route files for defining API endpoints.</li><li>index.ts: Main entry point of your application.</li></ul><p>userModel.ts (in src/models/):</p><pre>// userModel.ts<br>import mongoose from &quot;mongoose&quot;;<br><br>const userSchema = new mongoose.Schema({<br>  id: String,<br>  name: String,<br>  age: Number,<br>  origin: String,<br>  admin: Boolean,<br>});<br><br>export default mongoose.model(&quot;User&quot;, userSchema);</pre><p>userController.ts (in src/controllers/):</p><pre>import User from &quot;../models/userModel&quot;;<br><br>const findOne = async (id) =&gt; {<br>  try {<br>    return await User.findById(id);<br>  } catch (error) {<br>    console.error(&quot;Error finding user:&quot;, error);<br>    return null;<br>  }<br>};<br><br>export const readUsers = async () =&gt; {<br>  try {<br>    return await User.find();<br>  } catch (error) {<br>    console.error(&quot;Error fetching users:&quot;, error);<br>    return [];<br>  }<br>};<br><br>export const readUserById = async (id) =&gt; {<br>  try {<br>    const user = await findOne(id);<br>    if (user) {<br>      return user;<br>    } else {<br>      throw { status: 404, message: &quot;User not found&quot; };<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error fetching user:&quot;, error);<br>    throw error;<br>  }<br>};<br><br>export const createUser = async ({ body }) =&gt; {<br>  try {<br>    const newUser = new User(body);<br>    await newUser.save();<br>    return newUser;<br>  } catch (error) {<br>    console.error(&quot;Error creating user:&quot;, error);<br>    throw error;<br>  }<br>};<br><br>export const updateUser = async ({ body, params: { id } }) =&gt; {<br>  try {<br>    const existingUser = await findOne(id);<br>    if (existingUser) {<br>      await User.findByIdAndUpdate(id, body);<br>      return { ...existingUser.toObject(), ...body };<br>    } else {<br>      throw { status: 404, message: &quot;User not found&quot; };<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error updating user:&quot;, error);<br>    throw error;<br>  }<br>};<br><br>export const deleteUser = async ({ params: { id } }) =&gt; {<br>  try {<br>    const user = await findOne(id);<br>    if (user) {<br>      await User.findByIdAndDelete(id);<br>      return user;<br>    } else {<br>      throw { status: 404, message: &quot;User not found&quot; };<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error deleting user:&quot;, error);<br>    throw error;<br>  }<br>};</pre><p>userRoutes.ts (in src/routes/):</p><pre>import { t } from &quot;elysia&quot;;<br>import { readUsers, readUserById, createUser, updateUser, deleteUser } from &quot;../controllers/userController&quot;;<br><br>export default (app: any) =&gt; {<br>  app<br>    .get(&quot;/users&quot;, async () =&gt; {<br>      return await readUsers();<br>    })<br>    .get(&quot;/users/:id&quot;, async ({ params: { id }, set }: any) =&gt; {<br>      try {<br>        return await readUserById(id);<br>      } catch (error) {<br>        set.status = error.status || 500;<br>        return error.message || &quot;Internal Server Error&quot;;<br>      }<br>    })<br>    .post(&quot;/users&quot;, async ({ body }: any) =&gt; {<br>      try {<br>        return await createUser(body);<br>      } catch (error) {<br>        throw error;<br>      }<br>    }, { body: t.Object({ id: t.String(), name: t.String(), age: t.Number(), origin: t.String(), admin: t.Boolean() }) })<br>    .put(&quot;/users/:id&quot;, async ({ body, params: { id } }: any) =&gt; {<br>      try {<br>        return await updateUser({ body, params: { id } });<br>      } catch (error) {<br>        throw error;<br>      }<br>    }, { body: t.Object({ name: t.String(), age: t.Number(), origin: t.String(), admin: t.Boolean() }) })<br>    .delete(&quot;/users/:id&quot;, async ({ params: { id } }: any) =&gt; {<br>      try {<br>        return await deleteUser({ params: { id } });<br>      } catch (error) {<br>        throw error;<br>      }<br>    });<br>};</pre><p>index.ts (in src/):</p><pre>// index.ts<br>import { Elysia } from &quot;elysia&quot;;<br>import { swagger } from &quot;@elysiajs/swagger&quot;;<br>import mongoose from &quot;mongoose&quot;;<br>import userRoutes from &quot;./routes/ userRoutes&quot;;<br><br>// Connect to MongoDB<br>mongoose.connect(&quot;mongodb://localhost:27017/mydatabase&quot;);<br>const db = mongoose.connection;<br>db.on(&quot;error&quot;, console.error.bind(console, &quot;MongoDB connection error:&quot;));<br><br>const app = new Elysia()<br>  .use(<br>    swagger({<br>      documentation: {<br>        info: {<br>          title: &quot;Bun Elysia API Documentation&quot;,<br>          version: &quot;1.0.0&quot;,<br>        },<br>      },<br>    })<br>  );<br><br>// Register routes<br>userRoutes(app);<br><br>app.listen(3000);<br>console.log(`Elysia is running at ${app.server?.hostname}:${app.server?.port} by Ryan`);</pre><p>Keep learning guys ….</p><p><a href="https://github.com/aryan297">The Geek boy Blogs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1584c69c36bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spotify Clone(Playlist MicroService)using P2P and Nest JS]]></title>
            <link>https://medium.com/@aryanaman97/spotify-clone-playlist-microservice-using-p2p-and-nest-js-e48c4bc64443?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48c4bc64443</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[p2p]]></category>
            <category><![CDATA[spotify]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 10:33:58 GMT</pubDate>
            <atom:updated>2024-01-08T10:37:14.028Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a Spotify playlist clone with P2P network capabilities and server components using NestJS is a complex task. A full implementation of such a system would involve multiple components, including playlist management, user authentication, P2P networking, and more. Below is a simplified example that combines server-based operations with P2P synchronization. Please note that this example is illustrative, and a production-ready system would require more considerations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*898Hhix2HcHq6qk8Gow_8w.png" /><figcaption><a href="https://github.com/aryan297">The Geek Boy Blogs</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-bzaQs8TrRyjbeOTfw-zA.jpeg" /></figure><p>Install Required Packages:</p><pre>npm install @nestjs/core @nestjs/microservices @nestjs/typeorm typeorm libp2p</pre><p>Create User and Playlist Entities:</p><pre>// user.entity.ts<br>import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from &#39;typeorm&#39;;<br>import { Playlist } from &#39;./playlist.entity&#39;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  username: string;<br><br>  @OneToMany(() =&gt; Playlist, playlist =&gt; playlist.user)<br>  playlists: Playlist[];<br>}</pre><pre>// playlist.entity.ts<br>import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Entity()<br>export class Playlist {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  name: string;<br><br>  @ManyToOne(() =&gt; User, user =&gt; user.playlists)<br>  user: User;<br>}</pre><p>Create User and Playlist Services:</p><pre>// user.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(<br>    @InjectRepository(User)<br>    private userRepository: Repository&lt;User&gt;,<br>  ) {}<br><br>  async createUser(username: string): Promise&lt;User&gt; {<br>    const user = this.userRepository.create({ username });<br>    return await this.userRepository.save(user);<br>  }<br><br>  async getUserById(userId: number): Promise&lt;User&gt; {<br>    return await this.userRepository.findOne(userId);<br>  }<br>}</pre><pre>// playlist.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { Playlist } from &#39;./playlist.entity&#39;;<br><br>@Injectable()<br>export class PlaylistService {<br>  constructor(<br>    @InjectRepository(Playlist)<br>    private playlistRepository: Repository&lt;Playlist&gt;,<br>  ) {}<br><br>  async createPlaylist(name: string, userId: number): Promise&lt;Playlist&gt; {<br>    const playlist = this.playlistRepository.create({ name });<br>    playlist.user = { id: userId } as any; // Assuming you have a logged-in user<br>    return await this.playlistRepository.save(playlist);<br>  }<br><br>  async getPlaylistsByUserId(userId: number): Promise&lt;Playlist[]&gt; {<br>    return await this.playlistRepository.find({ where: { user: { id: userId } } });<br>  }<br>}</pre><p>Create User and Playlist Controllers:</p><pre>// user.controller.ts<br>import { Controller, Post, Body, Param, Get } from &#39;@nestjs/common&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Controller(&#39;users&#39;)<br>export class UserController {<br>  constructor(private readonly userService: UserService) {}<br><br>  @Post()<br>  async createUser(@Body() userData: { username: string }) {<br>    return await this.userService.createUser(userData.username);<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  async getUserById(@Param(&#39;id&#39;) userId: number) {<br>    return await this.userService.getUserById(userId);<br>  }<br>}</pre><pre>// playlist.controller.ts<br>import { Controller, Post, Body, Param, Get } from &#39;@nestjs/common&#39;;<br>import { PlaylistService } from &#39;./playlist.service&#39;;<br><br>@Controller(&#39;playlists&#39;)<br>export class PlaylistController {<br>  constructor(private readonly playlistService: PlaylistService) {}<br><br>  @Post()<br>  async createPlaylist(@Body() playlistData: { name: string, userId: number }) {<br>    return await this.playlistService.createPlaylist(playlistData.name, playlistData.userId);<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  async getPlaylistsByUserId(@Param(&#39;id&#39;) userId: number) {<br>    return await this.playlistService.getPlaylistsByUserId(userId);<br>  }<br>}</pre><p>Set Up P2P Module for Synchronization:</p><pre>// p2p.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { P2PController } from &#39;./p2p.controller&#39;;<br>import { UserService } from &#39;./user/user.service&#39;;<br>import { PlaylistService } from &#39;./playlist/playlist.service&#39;;<br><br>@Module({<br>  controllers: [P2PController],<br>  providers: [UserService, PlaylistService],<br>})<br>export class P2PModule {}</pre><pre>// p2p.controller.ts<br>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br>import { UserService } from &#39;./user/user.service&#39;;<br>import { PlaylistService } from &#39;./playlist/playlist.service&#39;;<br><br>@Controller(&#39;p2p&#39;)<br>export class P2PController {<br>  constructor(<br>    private readonly userService: UserService,<br>    private readonly playlistService: PlaylistService,<br>  ) {}<br><br>  @Post(&#39;sync/:sourceUserId/:targetUserId&#39;)<br>  async syncPlaylists(<br>    @Body() playlistData: { name: string },<br>    @Param(&#39;sourceUserId&#39;) sourceUserId: number,<br>    @Param(&#39;targetUserId&#39;) targetUserId: number,<br>  ) {<br>    // Fetch user and create playlist for source user<br>    const sourceUser = await this.userService.getUserById(sourceUserId);<br>    const sourcePlaylist = await this.playlistService.createPlaylist(<br>      playlistData.name,<br>      sourceUserId,<br>    );<br>     //Write your own P2P logic to get music from target user to source User<br><br>    // Sync playlists between source and target users (replace with actual P2P logic)<br>    // For simplicity, just add the source playlist to the target user&#39;s playlists<br>    const targetUser = await this.userService.getUserById(targetUserId);<br>    targetUser.playlists.push(sourcePlaylist);<br>    await this.userService.createUser(targetUser);<br><br>    return { success: true, playlists: targetUser.playlists };<br>  }<br>}</pre><pre>// main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { P2PModule } from &#39;./p2p/p2p.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.createMicroservice(P2PModule, {<br>    transport: Transport.TCP,<br>    options: {<br>      port: 3001,<br>    },<br>  });<br><br>  await app.listenAsync();<br>}<br><br>bootstrap();<br><br><br></pre><pre>npm run start</pre><p>Testing:</p><ul><li>Use tools like Postman or Insomnia to test your RESTful API endpoints in the UserController and PlaylistController.</li><li>To simulate P2P synchronization, you can call the /p2p/sync/:sourceUserId/:targetUserId endpoint to trigger the synchronization logic (replace this with actual P2P logic). For example, you can use Postman .</li></ul><p>Flow Chart</p><p>Creating a flow chart for a complex system involving NestJS, P2P networking, and multiple entities can be quite detailed. However, I’ll provide a simplified flow chart that outlines the core operations such as creating users, creating playlists, and simulating P2P synchronization. Note that this is a high-level representation, and in a real-world application, the flow would be more intricate.</p><p>Please use this as a starting point and modify it according to your specific application’s requirements.</p><pre>+------------------+          +-----------------+           +------------------+<br>|   User Creation  |          | Playlist Creation|           | P2P Synchronization|<br>+--------+---------+          +--------+--------+           +--------+---------+<br>         |                            |                            |<br>         v                            v                            |<br>+------------------+       +------------------+                 |<br>|   User Service   |       | Playlist Service |                 |<br>+--------+---------+       +--------+---------+                 |<br>         |                            |                            |<br>         v                            v                            |<br>+------------------+       +------------------+        +--------+---------+<br>|UserController    |       | PlaylistController|        | P2PController     |<br>+------------------+       +------------------+        +------------------+<br>         |                            |                            |<br>         v                            v                            |<br>+------------------+       +------------------+        +------------------+<br>|   TypeORM        |       |   TypeORM        |        | Custom P2P Logic  |<br>| (Database ORM)   |       | (Database ORM)   |        |    (e.g., libp2p)  |<br>+------------------+       +------------------+        +------------------+</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e48c4bc64443" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Handling of Large Dynamic Schemas with 100+ Fields in MongoDB using Nest.js]]></title>
            <link>https://medium.com/@aryanaman97/efficient-handling-of-large-dynamic-schemas-with-100-fields-in-mongodb-using-nest-js-fed43304a678?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fed43304a678</guid>
            <category><![CDATA[dynamic-schema]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 15:57:20 GMT</pubDate>
            <atom:updated>2024-01-03T15:57:20.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="The Geek Boy Blogs" src="https://cdn-images-1.medium.com/max/100/1*898Hhix2HcHq6qk8Gow_8w.png" /><figcaption><a href="http://github.com/aryan297">The Geek Boy Blogs</a></figcaption></figure><figure><img alt="Making features Possible" src="https://cdn-images-1.medium.com/max/1024/1*DVPL6-3HJJ7Y85z6hZbrKw.jpeg" /><figcaption>For those who love to solve problems</figcaption></figure><p>Handling a large number of dynamic fields in a MongoDB schema with NestJS requires careful consideration of the structure and organization of your data. While the class-validator and class-transformer approach is effective for a moderate number of fields, for a large number (100 fields or more), you might want to consider a more dynamic and flexible approach. Below is a simplified example using a dynamic schema for a user with a large number of fields:</p><p>Install Required Packages:</p><pre>npm install class-validator class-transformer @nestjs/mongoose mongoose</pre><p>Create a Dynamic User Schema with Mongoose:</p><pre>// dynamic-user.schema.ts<br>import * as mongoose from &#39;mongoose&#39;;<br><br>export const DynamicUserSchema = new mongoose.Schema({}, { strict: false });<br><br>export interface DynamicUser extends mongoose.Document {<br>  [key: string]: any;<br>}</pre><p>In this example, DynamicUserSchema is a MongoDB schema with strict: false, allowing you to dynamically add fields without defining them in advance. The DynamicUser interface represents the document structure.</p><p>Create a Dynamic User Service:</p><pre>// dynamic-user.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Model } from &#39;mongoose&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br><br>@Injectable()<br>export class DynamicUserService {<br>  constructor(@InjectModel(&#39;DynamicUser&#39;) private readonly userModel: Model&lt;DynamicUser&gt;) {}<br><br>  async createUser(userData: Record&lt;string, any&gt;): Promise&lt;DynamicUser&gt; {<br>    try {<br>      const createdUser = await this.userModel.create(userData);<br>      return createdUser;<br>    } catch (error) {<br>      throw new Error(&#39;Error creating user&#39;);<br>    }<br>  }<br>}</pre><p>Create a Dynamic User Controller:</p><pre>// dynamic-user.controller.ts<br>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br>import { DynamicUserService } from &#39;./dynamic-user.service&#39;;<br><br>@Controller(&#39;api/users&#39;)<br>export class DynamicUserController {<br>  constructor(private readonly userService: DynamicUserService) {}<br><br>  @Post()<br>  async createUser(@Body() userData: Record&lt;string, any&gt;) {<br>    try {<br>      const createdUser = await this.userService.createUser(userData);<br>      return { success: true, data: createdUser };<br>    } catch (error) {<br>      return { success: false, error: &#39;Internal Server Error&#39; };<br>    }<br>  }<br>}</pre><p>This approach allows you to handle a large number of dynamic fields without explicitly defining them in your code. However, keep in mind that managing such dynamic schemas can lead to challenges in terms of querying and indexing. It’s crucial to carefully design your data model based on the specific use case and access patterns in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed43304a678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Forms with NoSQL and Nest JS]]></title>
            <link>https://medium.com/@aryanaman97/dynamic-forms-with-nosql-and-nest-js-23b812ddaac7?source=rss-3f5f4a93838f------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b812ddaac7</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[dynamic-form]]></category>
            <category><![CDATA[mongoose]]></category>
            <dc:creator><![CDATA[Aryan aman]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 13:19:08 GMT</pubDate>
            <atom:updated>2024-01-03T13:48:42.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*898Hhix2HcHq6qk8Gow_8w.png" /></figure><h3>Dynamic Forms with NoSQL</h3><p>Using TypeScript in a NestJS application with NoSQL (MongoDB) has several benefits. Here are the key advantages</p><p>Type Safety:</p><ul><li>TypeScript adds static typing to JavaScript, which helps catch errors during development rather than at runtime.</li><li>Benefit: Improved code quality, fewer runtime errors, and better developer experience.</li></ul><p>Code Readability and Maintainability:</p><ul><li>TypeScript provides clear and explicit type annotations, making the code more readable and self-documenting.</li><li>Benefit: Easier collaboration, maintenance, and understanding of the codebase.</li></ul><p>Static Analysis:</p><ul><li>TypeScript’s static analysis allows for better code analysis and can catch potential issues before runtime.</li><li>Benefit: Early detection of bugs and improved code quality.</li></ul><p>Tooling and Community Support:</p><ul><li>TypeScript has strong community support and is backed by Microsoft. Many libraries and frameworks, including NestJS, provide first-class TypeScript support.</li><li>Benefit: Access to a large ecosystem of libraries, tools, and resources.</li></ul><p>Adding some code Snippet to start with Nest JS, we need below package.</p><pre>npm install @nestjs/core @nestjs/common @nestjs/mongoose mongoose body-parser</pre><pre><br>// app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br><br>@Module({<br>  imports: [MongooseModule.forRoot(&#39;mongodb://localhost:27017/your-database-name&#39;),],<br>  controllers: [AppController],<br>})<br>export class AppModule {}</pre><pre>// app.controller.ts<br>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br>import { InjectModel } from &#39;@nestjs/mongoose&#39;;<br>import { Model } from &#39;mongoose&#39;;<br><br>@Controller(&#39;api/forms&#39;)<br>export class AppController {<br>  constructor(@InjectModel(&#39;Form&#39;) private readonly formModel: Model&lt;any&gt;) {}<br><br>  @Post()<br>  async createForm(@Body() formData: any) {<br>    try {<br>      const createdForm = await this.formModel.create(formData);<br>      return { success: true, data: createdForm };<br>    } catch (error) {<br>      return { success: false, error: &#39;Internal Server Error&#39; };<br>    }<br>  }<br>}</pre><p>Define a separate Schema for this .</p><p>Schema can be Array or Object , according to your Need.</p><pre>// form.schema.ts<br>import * as mongoose from &#39;mongoose&#39;;<br><br>export const FormSchema = new mongoose.Schema({<br>  // Define your dynamic form fields in the schema<br>});<br><br>export interface Form extends mongoose.Document {<br>  // Define the interface for your form data<br>}</pre><p>Update Your app.module.ts file</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { FormSchema } from &#39;./form.schema&#39;; // Import the schema<br><br>@Module({<br>  imports: [MongooseModule.forRoot(&#39;mongodb://localhost:27017/your-database-name&#39;), MongooseModule.forFeature([{ name: &#39;Form&#39;, schema: FormSchema }])],<br>  controllers: [AppController],<br>})<br>export class AppModule {}</pre><p>Additional Point for handling ticketing Schema we have like this</p><pre>// ticket.schema.ts<br>import * as mongoose from &#39;mongoose&#39;;<br><br>export const TicketSchema = new mongoose.Schema({<br>  title: {<br>    type: String,<br>    required: true,<br>    trim: true,<br>  },<br>  description: {<br>    type: String,<br>    required: true,<br>    trim: true,<br>  },<br>  category: {<br>    type: String,<br>    enum: [&#39;Bug&#39;, &#39;Feature Request&#39;, &#39;Question&#39;, &#39;Other&#39;],<br>    required: true,<br>  },<br>  priority: {<br>    type: String,<br>    enum: [&#39;Low&#39;, &#39;Medium&#39;, &#39;High&#39;],<br>    default: &#39;Medium&#39;,<br>    required: true,<br>  },<br>  status: {<br>    type: String,<br>    enum: [&#39;Open&#39;, &#39;In Progress&#39;, &#39;Resolved&#39;, &#39;Closed&#39;],<br>    default: &#39;Open&#39;,<br>    required: true,<br>  },<br>  createdAt: {<br>    type: Date,<br>    default: Date.now,<br>  },<br>});<br><br>export interface Ticket extends mongoose.Document {<br>  title: string;<br>  description: string;<br>  category: &#39;Bug&#39; | &#39;Feature Request&#39; | &#39;Question&#39; | &#39;Other&#39;;<br>  priority: &#39;Low&#39; | &#39;Medium&#39; | &#39;High&#39;;<br>  status: &#39;Open&#39; | &#39;In Progress&#39; | &#39;Resolved&#39; | &#39;Closed&#39;;<br>  createdAt: Date;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b812ddaac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>