<?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 Ildar Timerbaev on Medium]]></title>
        <description><![CDATA[Stories by Ildar Timerbaev on Medium]]></description>
        <link>https://medium.com/@dkildar?source=rss-962eedb6d022------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ePvXGkcVr09sazCa1knOVg@2x.jpeg</url>
            <title>Stories by Ildar Timerbaev on Medium</title>
            <link>https://medium.com/@dkildar?source=rss-962eedb6d022------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:52:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dkildar/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[I Built My Own Error Tracker]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://dkildar.medium.com/i-built-my-own-error-tracker-aead7d2c86c6?source=rss-962eedb6d022------2"><img src="https://cdn-images-1.medium.com/max/2600/1*lYTGcqKBbDu9wLQU6ObHnw.png" width="2800"></a></p><p class="medium-feed-snippet">Every production application eventually crashes. I don&#x2019;t mind runtime errors. What I do mind is spending hours trying to understand what&#x2026;</p><p class="medium-feed-link"><a href="https://dkildar.medium.com/i-built-my-own-error-tracker-aead7d2c86c6?source=rss-962eedb6d022------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://dkildar.medium.com/i-built-my-own-error-tracker-aead7d2c86c6?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/aead7d2c86c6</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 21:05:12 GMT</pubDate>
            <atom:updated>2026-07-22T18:41:48.519Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Flexible entities using TypeScript]]></title>
            <link>https://medium.com/weekly-webtips/flexible-entities-using-typescript-772dd7aa921f?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/772dd7aa921f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 09:23:00 GMT</pubDate>
            <atom:updated>2024-02-01T09:23:00.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1r8psNYQSx47nHgExo_mjQ.png" /></figure><p>In this article, we will discuss about a new way to work with entities for data transfer in between server and client side.</p><p>Hi! My name is Ildar. I am a developer with more than 6 years of experience, mostly working with frontend technologies. Every developer faces different entities on the client side, which are returned by the API. These entities might be static, like simple JSON objects, or class instances with computed values or built-in methods. Over the last couple of years, I’ve worked very closely with entities and have figured out exactly how I want to interact with them.</p><h3>Motivation</h3><p>During my career, all projects I’ve worked on have used JSON as the transfer object between the server and client side.</p><p>Every time the client fetches some data from an API, it receives a plain JSON-object. Simple cases may be handled with the raw JSON-object, but most require some additional work before passing this entity to the UI. A few obvious examples include converting date values in ISO or timestamp format to a Date class instance, converting numeric values to boolean (0 or 1), and computing a full name based on first and last names.</p><p>All this additional work needs to be done somewhere, and since JavaScript doesn’t have convenient built-in tools for that, the developer must do it manually. Let’s see how we can create an entity with native JS and list the related pros and cons for each approach.</p><h4>Class based</h4><pre>class User {<br>  firstName: string<br>  lastName: string<br><br>get fullName(): string {<br>    return `${firstName} ${lastName}`<br>  }<br>  constructor(jsonData: Record&lt;string, unknown&gt;) {<br>    if (typeof jsonData.firstName === &#39;string&#39;) {<br>      this.firstName = jsonData.first_name<br>    }<br>    if (typeof jsonData.lastName === &#39;string&#39;) {<br>      this.firstName = jsonData.last_name<br>    }<br>  }<br>}</pre><p>As you can see in the example above, we can create an entity class. Obviously, entities contain many more fields than in our example, and our code will be large and will contain much boilerplate code.</p><p><strong>Pros</strong></p><ul><li>Logic encapsulation — all logic related to the entity is encapsulated inside one class/file;</li><li>Safe type — const user = new User(jsonData) guarantees us that user will always be an instance of User(assuming the prototype wasn’t changed).</li></ul><p><strong>Cons</strong></p><ul><li>There is a lot of boilerplate code for transforming, computing, and mutating.</li></ul><h4>Object based</h4><pre>interface User {<br>  first_name: string<br>  last_name: string<br>  birth: string<br>}<br><br>const user: User = {<br>  first_name: &#39;Ildar&#39;,<br>  last_name: &#39;Timerbaev&#39;,<br>  birth: &#39;1996-06-16T00:00:00Z&#39;<br>}<br><br>function getUserBirthDate(user: User) {<br>  return new Date(user.birth)<br>}<br><br>function getFullName(user: User) {<br>  return `${user.first_name} ${user.last_name}`<br>}</pre><p><strong>Pros</strong></p><ul><li>No need to write an additional class — less code;</li></ul><p><strong>Cons</strong></p><ul><li>Misses logic encapsulation;</li><li>Entity type is always an object and we cannot detect which entity came to the UI (for example, in React props);</li><li>A lot of boilerplate code for transforming, computing, mutating.</li></ul><p>As you can see, both approaches have their own pros and cons. But what if there is another way?</p><h3>Meet immutable-entity-manager</h3><p>After facing object-based and class-based issues multiple times, I decided to implement a new tool for managing entities declaratively and without boilerplate code. Meet <a href="https://github.com/dkildar/immutable-entity-manager">https://github.com/dkildar/immutable-entity-manager</a>.</p><p>Basically, this package represents a convenient tool for declaring and parsing entities. Let’s see its basic usage.</p><pre>@ImmutableEntity()<br>class Person {<br>  readonly firstName!: string<br>  readonly lastName!: string<br>  @ImmutableEntityTyped(Date) readonly birthDate!: Date<br>}<br><br>const person = ImmutableEntityManager<br>  .getUniqueManager(Person)<br>  .parseFromJson({<br>    first_name: &#39;hello&#39;,<br>    last_name: &#39;world&#39;,<br>    birth_date: &#39;2023-12-15T11:01:22.041Z&#39;<br>  })<br>  .build()</pre><p>Immutable entity manager is two instruments: entity declaration and its Manager/Builder.</p><h4>Entity declaration</h4><p>An entity should be declared as a simple class with a set of properties. The @ImmutableEntity decorator allows the Manager to parse and fill properties according to their rules and options. Each property will be immutable, which guarantees that the property type won’t change in the future, ensuring type-safety.</p><p><strong>Transforming</strong></p><p>Any property can be automatically transformed into another class instance using the @ImmutableEntityTyped decorator. This allows us not to worry about String, Number, Boolean, Date, or any other class that accepts a value in the constructor.</p><p>This decorator can also parse another Immutable entity recursively or an array of values. Therefore, our entity could be like:</p><pre>@ImmutableEntity()<br>class Media {<br>  link: string<br>}<br><br>@ImmutableEntity()<br>class User {<br>  @ImmutableEntityTyped(Media) avatar: Media<br>  @ImmutableEntityTyped(Media) poster: Media<br>  @ImmutableEntityTyped(Media) album: Media[]<br>}</pre><p><strong>Default values</strong></p><p>Any property might fall back to default value if value won’t be found in the parsing JSON-object.</p><pre>@ImmutableEntity()<br>class User {<br>  @ImmutableEntityDefault(&#39;active&#39;) status: string<br>}</pre><p><strong>Transients</strong></p><p>Any property might be ignored while parsing if property has @ImmutableEntityTransient decorator.</p><h4>Manager and builder</h4><p><strong>Manager</strong> represents the parser of an entity. Currently, it allows developers to parse JSON data and create a builder instance.</p><p><strong>Builder</strong> represents the standard entity builder pattern. The Builder is exported and can be created directly, but the best method is to use the manager’s parsing result object. The Builder allows developers to modify the given JSON-object, set new properties, or disable decorators.</p><pre>const builder = ImmutableEntityManager<br>  .getUniqueManager(Person)<br>  .parseFromJson({<br>      ...<br>  })<br><br>builder<br>  .withProperty(&#39;someProperty&#39;, someValue)<br>  .withProperty(&#39;someAnotherProperty&#39;, someAnotherValue)<br>  .build()</pre><h3>Out of main scope</h3><p>Different APIs uses different cases in JSON. Builder may accept special options for auto-converting cases.</p><pre>builder.withOptions({ camelToSnakeCase: true }) // camelToSnakeCase | snakeToCamelCase</pre><p>I hope many developers will find this package helpful. I have a lot of plans in Roadmap, You may see it in source.</p><p>Thanks for the reading!</p><p>Source: <a href="https://github.com/dkildar/immutable-entity-manager">immutable-entity-manager</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772dd7aa921f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/flexible-entities-using-typescript-772dd7aa921f">Flexible entities using TypeScript</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React query for data streaming]]></title>
            <link>https://dkildar.medium.com/react-query-for-data-streaming-c926eb0a562e?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/c926eb0a562e</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 08:43:13 GMT</pubDate>
            <atom:updated>2023-11-27T08:43:38.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VSZC5o9-wbaNFLa9K6WYw.jpeg" /></figure><h3>Introduction</h3><p>Everyone is familiar with the popular framework for managing API requests — <a href="https://www.npmjs.com/package/@tanstack/react-query">@tanstack/react-query</a>. This framework is designed for handling browser HTTP API requests. However, that’s not the only way to use it. React query also supports any promises within queries and mutations, which assists us in setting up data streaming and react query together. Let’s get started!</p><h3>Theory</h3><h4>Client setup</h4><p>Since We want to handle data streaming then We assume to use a some kind of WebSocket with STOMP for it. Let’s imagine that We have very simple data flow.</p><pre>const stompClient = new StompClient()<br>stompClient.subscribe((event) =&gt; {...})<br>stompClient.publish(&#39;mychannel, {...})</pre><p>To gain access from any part of our application, we should position this client within the React context, which will be provided in the root component. Currently, this context will only contain a client instance for accessing our queries and mutations.</p><pre>const StompContext = createContext({<br> client: undefined<br>})<br><br>function StompManager({ children }: PropsWithChildren) {<br> const [client, setClient] = useState(new StompClient())<br><br> return &lt;StompContext.Provider value={{ client }}&gt;{children}&lt;/StompContext.Provider&gt;<br>}<br><br>function useStompManager() {<br> const { client } = useContext(StompContext)<br> return client<br>}</pre><h4>Query</h4><p>Let’s revisit how queries work. They consist of an identification key, a query function, and options. Since the identification key is self-explanatory, we’ll focus on the query function and options.</p><p>Firstly, each query should only be activated when our client is ready.</p><pre>const client = useStompManager()<br>...<br>useQuery([QueryKey], () =&gt; {...}, { enabled: !!client })</pre><p>Secondly, each query requires a function to subscribe to the channel and wait for new data. There are several different subscription types:</p><ol><li>One event subscription — This is a pattern where we receive something from the channel and then complete the subscription (e.g., getting a user profile).</li><li>Infinite event subscription — This is a pattern where we listen to the channel until it’s unsubscribed or cancelled (e.g., listening to chat messages). Each subscription should be stored in a subscriptions storage to avoid generating multiple subscriptions on each query call.</li></ol><p>Since we may have infinite queries, we need to create a subscriptions storage in the StompContext. For this, I&#39;ll use the useMap hook from the react-use package. Let&#39;s establish a rule that the subscription identifier is the query key.</p><pre>const [subscribers, { set, get }] = useMap&lt;Record&lt;string, boolean&gt;&gt;();</pre><h4>Mutation</h4><p>The implementation of mutations can vary depending on the protocol used. For instance, chat messages could return a sent message in a channel, indicating successful transmission. However, this is a unique case. Suppose the STOMP client has a publish method that returns a promise. In that case, this mutation doesn&#39;t have any specific logic.</p><pre>function useStompMutation(mutationKey: string, destination: string) {<br>  // getting client<br>  // default useMutation hook with sending the message in mutation function<br>}</pre><p><em>Sending without confirmation</em></p><pre>function useStompConfirmableMutation(mutationKey: string, channel: string, destination: string) {<br>  // getting client<br>  // default useMutation hook with next mutation function:<br>  // 0. Return the promise with resolve, reject parameters<br>  // 1. Subscribing to specific channel and resolving the promise there<br>  // 2. Sending a message based on mutation function parameters<br>  // 3. Handling error to reject the promise<br>}</pre><p><em>Sending with confirmation</em></p><h3>Implementation</h3><h4>One event query</h4><pre>function listenOnce(client: StompClient, channel: string) {<br> return new Promise((resolve, reject) =&gt; {<br> const sub = client.subscribe(channel, event =&gt; {<br>   sub.unsubscribe()<br>   resolve(event)<br>  })<br> })<br>}</pre><pre>function useStompQuery&lt;DATA, ERROR&gt;(<br> queryKey: QueryKey, <br> channel: string,<br> options?: UseQueryOptions&lt;DATA, ERROR&gt;<br>) {<br> const client = useStompClient()<br> return useQuery(<br>  queryKey, <br>  async () =&gt; listenOnce(),<br>  {<br>   ...options,<br>   enabled: !!client &amp;&amp; (options?.enabled ?? true),<br>  }<br>}</pre><h4>Infinite events query</h4><pre>function useStompQuery&lt;DATA, ERROR&gt;(<br> queryKey: QueryKey, <br> channel: string,<br> newDataResolver: (previousData: DATA[], newComingData: DATA) =&gt; void,<br> options?: UseQueryOptions&lt;DATA[], ERROR&gt;,<br>) {<br> const client = useStompClient()<br> const { setSubscriber, getSubscriber } = useContext(StompContext)<br> const queryClient = useQueryClient()<br><br> // Hook from react-use package<br> useMount(() =&gt; {<br>  if (getSubscriber(queryKey)) {<br>   return<br>  }<br><br>  const sub = client.subscribe(channel, event =&gt; {<br>   const previousData = queryClient.getQueryData&lt;DATA[]&gt;(queryKey)<br>   let nextData = newDataResolver(previousData, event)<br>   queryClient.setQueryData(queryKey, nextData)<br>  })<br>  setSubscriber(queryKey, sub)<br>  })<br><br> return useQuery&lt;DATA[]&gt;(<br>  queryKey,<br>  () =&gt; queryClient.getQueryData&lt;DATA[]&gt;(queryKey),<br>  {<br>   ...options,<br>   enabled: !!client &amp;&amp; (options?.enabled ?? true),<br>  }<br>}</pre><p>Let’s highlight an implementation details:</p><ul><li>newDataResolver – special mutating function that allow us to control each new event coming(e.g. whenever new message coming then We could mark it with <em>sent</em> status);</li><li>() =&gt; queryClient.getQueryData&lt;DATA[]&gt;(queryKey) – as this query hasn’t one-time fetching function then We have to return the query itself data on each refetch.</li></ul><h4>Mutation without confirmation</h4><pre>function useStompMutation&lt;T, DATA&gt;(<br> mutationKey: string, <br> destination: string,<br> options?: UseMutationOptions&lt;DATA&gt;<br>) {<br> const client = useStompClient()<br> return useMutation&lt;DATA&gt;(<br>  mutationKey, <br>  async (message: T) =&gt; {<br>   if (!client) {<br>    throw new Error(&#39;Client not found&#39;)<br>   }<br>   client.publish(destination, message)<br>  },<br>  options<br> ) <br>}</pre><h4>Mutation with confirmation</h4><pre>function useStompConfirmableMutation&lt;T, DATA&gt;(<br> mutationKey: string, <br> destination: string,<br> channel: string,<br> confirmation?: (event: DATA) =&gt; boolean,<br> options?: UseMutationOptions&lt;DATA&gt;<br>) {<br> const client = useStompClient()<br> return useMutation&lt;DATA&gt;(<br>  mutationKey, <br>  async (message: T) =&gt; new Promise(async (resolve, reject) =&gt; {<br>   if (!client) {<br>    throw new Error(&#39;Client not found&#39;)<br>   }<br><br>   client.subscribe(channel, event =&gt; {<br>    if (confirmation(event)) {<br>     resolve(event)<br>    }<br>   })<br><br>   try {<br>    await client.publish(destination, message)<br>   } catch (e) {<br>    reject(e)<br>   }<br>  }),<br>  options<br> ) <br>}</pre><p>The potential issue here is that if the event doesn’t return in the channel, it may cause an infinite promise. Implementing timeout rejection could resolve this, but I’ll leave that up to you 🙂</p><p>We’ve successfully implemented a working solution for data streaming in React Query. However, this solution may not be ideal for all use-cases, so you might need to adjust it depending on your data streaming service implementation.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c926eb0a562e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I found own way to access Redux in React component]]></title>
            <link>https://medium.com/weekly-webtips/how-i-found-own-way-to-access-redux-in-react-component-a3272765367b?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3272765367b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 13:03:31 GMT</pubDate>
            <atom:updated>2023-02-20T13:03:31.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsfrNpkBgDAPT3zKqkLxcQ.jpeg" /></figure><p>Hello, there!</p><p>I’ve seen a lot of more articles about React and Redux combination and most of them explaining how to connect these solutions and basic usage. But lets imagine that We have a project a bit larger than the regular todo-list example. Our project have a store with a lot of different modules and hundreds actions.</p><p>I would like to show You how I created my own solution without any built-in solutions or packages.</p><h3>Trivial solutions</h3><h4>Props way</h4><p>The most trivial and easy solution is a providing a store state and actions via props. I won’t describe a full example here You know how it works.</p><pre>connect(mapStateToProps, (dispatch: Dispatch&lt;AnyAction&gt;) =&gt;<br>  bindActionCreators({&lt;actions_object&gt;}, dispatch))(MyComponent)</pre><p><strong>Pros: </strong>Easy to use, fast solution, reactive as well.<br><strong>Cons:</strong> Need to provide each store state item or action manually to a child component(Of course, You may connect each component to the store but there will be a very high-weight components).</p><h4>Built-in hooks way</h4><p>Latest versions of Redux offers us several hooks for accessing to store like:</p><ol><li>useStore — get the store instance directly;</li><li>useDispatch — get a dispatch function;</li><li>useSelector — build a reactive getter from store;</li></ol><p><strong>Pros: </strong>Easy to use, fast, partial reactive;<br><strong>Cons:</strong> useStore isn’t reactive at all – You may get a state but it will be the snapshot only – not applicable. useSelector isn’t convenient to get a lot of data. You may try to select the whole state and destruct gotten object but it will return the new value each time when main state will be changed. It may cause unexpected behavior.</p><h3>My solution</h3><p>Let’s start with a defining of what we need. I would like to make a hook which will allow getting any state module, property as reactive and getting any action. It should support TypeScript as well, obviously.</p><p>Actually, we have to remember about performance and convenience. So, let’s see how it should be used:</p><pre>const { someState, someAction } = ourHook() // someState and someAction provide types automatically -</pre><p>Let’s start with creating of custom hook.</p><pre>const useMappedStore = () =&gt; {<br>  return {...state, ...actions}; // Typed<br>}</pre><p>Firstly, I have to map the store actions, make them dispatchable and return to component. It could be achieved with the built-in redux function bindActionCreators(actionsObj, dispatch).</p><p>Secondly, need to get store state reactively. We may achieve it with hooks above. But how we can get a state dynamically and reactively?</p><p>Let’s use a one interest instrument named as Proxy.</p><pre>export const useMappedStore = () =&gt; {<br>  const store = useStore&lt;AppState&gt;();<br>  const dispatch = useDispatch();<br><br>  const storeStateAccessor: AppState = store.getState();<br>  const storeStateAccessorProxy = new Proxy&lt;AppState&gt;(storeStateAccessor, {<br>    get(target, p, receiver) {<br>      return useSelector((state) =&gt; state[p]);<br>    }<br>  });<br><br>  return {<br>    ...storeStateAccessorProxy,<br>    ...bindActionCreators(getActions(), dispatch)<br>  };<br>};</pre><p>As you can see I used a proxy to creating a selector hook dynamically. Any store state property will be called when component will be created. Pay attention we are not breaking hooks rules.</p><p><em>If We have to support old browsers We could use </em><em>Object.defineProperty as well.</em></p><h3>Instead of conclusion</h3><p>I know NPM has a thousands redux helper packages and I just wanted to show you how developer could implement it manually.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3272765367b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/how-i-found-own-way-to-access-redux-in-react-component-a3272765367b">How I found own way to access Redux in React component</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular – Custom RxJS State Manager]]></title>
            <link>https://medium.com/weekly-webtips/angular-custom-rxjs-state-manager-40f2983dc63a?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f2983dc63a</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 14:38:24 GMT</pubDate>
            <atom:updated>2021-10-03T07:40:32.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cprry1Fiij--DSL8fwTcdg.jpeg" /></figure><p>Hello there!</p><p>All developers will work with a large data in the project. Early or lately simple solutions won’t work and for access or modify data You will have to use the State Management pattern.</p><p>Angular Framework has great solutions such as NGRX, NGXS, or another Redux-like package. These packages are wonderful solutions if you have very large data and enough time for writing code. The main problem with these packages is a lot of boilerplate code.</p><h3>Simple state management</h3><p>Let’s start with a simple example. We have a movie collection, movie and actor models with computed values for retrieve data, and methods for writing new data.</p><pre>abstract class Identifiable {<br>  public id: number;<br>}</pre><pre>class Actor extends Identifiable {<br>  public name: string;<br>}</pre><pre>class Movie extends Identifiable {<br>  private actors: Map&lt;Identifiable[&#39;id&#39;], Actor&gt;;<br>  public title: string;</pre><pre>  public setActors(actors: Actor[]): Actor[] {<br>    this.actors = new Map(actors.map(actor =&gt; [actor.id, actor]));<br>  }<br>}</pre><pre>class MovieCollection extends Identifiable {<br>  private movies: Map&lt;Identifiable[&#39;id&#39;], Movie&gt;;<br>  public title: string;</pre><pre>  public setMovies(movies: Movie[]): Actor[] {<br>    this.movies = new Map(movies.map(actor =&gt; [movie.id, movie]));<br>  }<br>}</pre><p>Let’s write the service to managing these models:</p><pre>@Injectable()<br>export class MovieCollectionService {<br>  public <strong>collection</strong>: MovieCollection;<br>}</pre><h3>Reactive State Management issue</h3><p>Now We can simply retrieve and modify collection in the service methods. As you know Angular Framework perfectly working with Rx.js. It gives us dynamic data streaming: we can modify our data in one place and stream it to all subscribers. So We can update our service and add the ReplaySubject there: it will store an actual copy of the collection and stream to all subscribers.</p><pre>@Injectable()<br>export class MovieCollectionService {<br>  private <strong>collectionSubject</strong> = new ReplaySubject&lt;MovieCollection&gt;(1);<br>  public <strong>collection$</strong> = this.collectionSubject.asObservable();<br>}</pre><p>It works perfectly with exception of modifying. We should get our collection copy from the subject, modify it and push it to the Subject next. Let’s see how it will looks if we want to set movies to a movie collection.</p><pre>...<br>public getCollectionMoviesList(): Observable&lt;any&gt; {<br>  const <strong>request$</strong> = this.httpClient.post(...);<br>  return zip(<strong>this.collection$</strong>, <strong>request$</strong>).pipe(<br>    tap(([collection, response]) =&gt; {<br>      collection.setMovies(response);<br>      <strong>this.collectionSubject</strong>.next(collection);<br>    });<br>  );<br>}<br>...</pre><p>As you can see our method looks not very obvious because for one HTTP API request we should zip two observables and push the next copy. When your methods will be a little bit more then this boilerplate code will increase fast.</p><h3>Reactive model with TypeScript Decorators</h3><p>We can use TypeScript Decorators to solve the problem of boilerplate code with saving models structure. So let’s create a decorator which will make our model reactive: We will extend our class. Need to:</p><ol><li>Declare private class property for storing our model snapshot(_stateStorage$);</li><li>Describe the private class method for pushing the next updated model snapshot(_updateState);</li><li>Register all snapshots getters – assign the snapshot storage observables to them(_snapshots);</li></ol><pre><strong>export function </strong><em>ReactiveEntity</em>(): ClassDecorator {<br>  <strong>return function</strong>(target: <strong>any</strong>) {<br>    <strong>const </strong>newTarget = target;<br>    newTarget.<strong>prototype</strong>.<strong>_stateStorage$ </strong>= <strong>new </strong>ReplaySubject(1);<br>    newTarget.<strong>prototype</strong>._updateState = <strong>function</strong>() {<em><br>      </em><strong>this</strong>.<strong>_stateStorage$</strong>.next(<strong>this</strong>);<br>    }<br>    newTarget.<strong>prototype</strong>.<strong>_snapshots</strong>.forEach(key =&gt; newTarget.<strong>prototype</strong>[key] = newTarget.<strong>prototype</strong>.<strong>_stateStorage$<br>      </strong>.asObservable().pipe(<em><br>        tap</em>(state =&gt; !state ? <strong>this</strong>.<strong>_stateStorage$</strong>.next(<strong>this</strong>) : <strong>null</strong>))<br>    );<br>    <strong>return </strong>newTarget;<br>  }<br>}</pre><p>Now We have to describe snapshots getters. It’s a class property that will be decorated with the Reactive Snapshot decorator and will return Observable of a state. Let’s implement it. In this decorator, We simply register the property as a snapshot getter.</p><pre><strong>export function </strong><em>ReactiveSnapshot</em>(): PropertyDecorator {<em><br>  </em><strong>return function</strong>(target: <strong>any</strong>, propertyKey) {<br>    <strong>if </strong>(!target.<strong>_snapshots</strong>) {<br>      target.<strong>_snapshots </strong>= [];<br>    }<br>    target.<strong>_snapshots</strong>.push(propertyKey);<br>  }<br>}</pre><p>Finally need to implement updating of the reactive state in class mutation methods. As You might have guessed it’s a decorator too. We extend the base class method: call the original method before then push the current model state to state storage.</p><pre><strong>export function </strong><em>UpdateReactiveState</em>(): MethodDecorator {<em><br>  </em><strong>return function</strong>(target: <strong>any</strong>, propertyKey, descriptor) {<br>    <strong>const </strong>originalMethod = descriptor.<strong>value</strong>;<em><br>    </em>descriptor.<strong>value </strong>= <strong>function</strong>(...args: <strong>any</strong>[]) {<br><em>      </em><strong>const </strong>result = originalMethod.apply(<strong>this</strong>, args);<br><em>      </em><strong>this</strong>._updateState();<br>      <strong>return </strong>result;<br>    }<br>  }<br>}</pre><p>Our reactive model was implemented. Let’s see how it looks.</p><pre>@ReactiveEntity()<br>class MovieCollection extends Identifiable {<br>  private <strong>movies</strong>: Map&lt;Identifiable[&#39;id&#39;], Movie&gt;;<br>  public <strong>title</strong>: string;</pre><pre>  @ReactiveSnapshot()<br>  public <strong>snapshot$</strong>: Observable&lt;this&gt;;</pre><pre>  @UpdateReactiveState()<br>  public setMovies(movies: Movie[]): Actor[] {<br>    <strong>this.movies</strong> = new Map(movies.map(actor =&gt; [movie.<strong>id</strong>, movie]));<br>  }<br>}</pre><p>Now We can simply update the model and stream all changes with a built-in reactive state.</p><p>Support us by following our telegram <a href="https://t.me/frontend_html_css_js">channel</a>. We post a lot of helpful information about web development every day.</p><p>That’s all! Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f2983dc63a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/angular-custom-rxjs-state-manager-40f2983dc63a">Angular – Custom RxJS State Manager</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular – Auto-unsubscribe for RxJS]]></title>
            <link>https://medium.com/weekly-webtips/angular-auto-unsubscribe-for-rxjs-e78047856a73?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/e78047856a73</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 19:22:31 GMT</pubDate>
            <atom:updated>2021-09-28T08:54:54.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qsKWRRZ3Om4OUH-lncATQ.jpeg" /></figure><p>Hello dear readers! Angular is a very powerful framework. A huge part of this framework and not less by power is ReactiveJS. Angular uses Rxjs almost everywhere. But Rxjs has a little, not obvious mechanism called Subscriptions.</p><p>Rxjs observable is lazy. So you have to subscribe to an observable to start data streaming. When we subscribe we should unsubscribe later. Anyway. If we will do a subscription in a component and change some state or there are operations that can change state outside of component we have a potentially risky subscription. What does it mean? With this subscription, we can’t say that the current state is valid because it can be changed from an unexpected place. Let’s reproduce it in the example below.</p><pre>@Component(...)<br>export class MyComponent {</pre><pre>  constructor(private apiService: MyApiService) {}</pre><pre>  public ngOnInit(): void {<br>    this.apiService<br>      .callSomeServerApi()<br>      .subscribe(() =&gt; window.location = &#39;https://another.site`)<br>  }</pre><pre>}</pre><p>So if we destroy MyComponent for some reason(e.g. *ngIf directive) and we have a very slow connection to the server then after destroying the component we still will wait for the response from the HTTP request and in a successful case, we will be redirected. In sum, we destroyed the component and do not expect any action from it, but the subscription is still alive.</p><h3>Built-in subscriptions manage</h3><p>As the solution to these problems, we can unsubscribe before a component will destroy.</p><h4>Automatically unsubscribe with async pipe</h4><p>The most right solution is to do subscriptions in the template with the async pipe. Its built-in pipe will subscribe on component view initialization and will unsubscribe when a component will be destroyed.</p><p>But this solution not working if we use subscription in directives or can’t subscribe in templates.</p><h4>Manually unsubscribe with Subscription</h4><p>We can store subscriptions as component property and unsubscribe in the onDestroy hook. But this solution requires a lot of boilerplate code(see below).</p><pre>@Component(...)<br>export class MyComponent implements OnDestroy {<br>  private subscription: Subscription; // boilerplate</pre><pre>  constructor(private apiService: MyApiService) {}</pre><pre>  public ngOnInit(): void {<br>    this.subscription = this.apiService // boilerplate<br>      .callSomeServerApi()<br>      .subscribe(() =&gt; window.location = &#39;https://another.site`)<br>  }</pre><pre>public ngOnDestroy(): void {<br>    if (this.subscription) { // boilerplate<br>      this.subscription.unsubscribe(); // boilerplate</pre><pre>    } // boilerplate</pre><pre>  }</pre><pre>}</pre><h4>Manually unsubscribe with takeUntil operation</h4><p>Also, we can use takeUntil operation and Rxjs Subject for manage subscriptions (see below). This format also has a lot of boilerplate code.</p><pre>@Component(...)<br>export class MyComponent implements OnDestroy {<br>  private unsubscribe: Subject; // boilerplate</pre><pre>  constructor(private apiService: MyApiService) {}</pre><pre>  public ngOnInit(): void {<br>    this.subscription = this.apiService<br>      .callSomeServerApi()<br>      .pipe(takeUntil(this.unsubscribe)) // boilerplate<br>      .subscribe(() =&gt; window.location = &#39;https://another.site`)<br>  }</pre><pre>  public ngOnDestroy(): void {<br>    this.unsubscribe.next(); // boilerplate<br>    this.unsubscribe.complete(); // boilerplate</pre><pre>  }</pre><pre>}</pre><h3>How to unsubscribe automatically</h3><p><em>Digression: We have a lot of subscriptions in our work project and we can’t use the async pipe. Project architecture allows us to use only directives and components. So we have about 50 directives and </em>s<em>lightly fewer components. We can’t afford to write boilerplate code with Subscription or takeUntil operation. So we wanted to write an easy-to-use mechanism that will unsubscribe automatically.</em></p><p>We should store our subscriptions in components and unsubscribe them when the component destroying. The best place for it is theOnDestroy hook. Also, our solution should work in AOT and JIT modes.</p><h4>@AutoUnsubscribe</h4><p>Since we use TypeScript and Angular Framework the best mechanism for manage subscriptions is property decorators. The full code of decorator is below.</p><pre>export function AutoSubscribe(target: any, key: string, descriptor: PropertyDescriptor): void {<br>  const originalOnDestroy = target.ngOnDestroy;<br>  target._subscriptions = target._subscriptions || new Map&lt;string, Subscription&gt;();<br>  const originalMethod = descriptor.value;<br><br>  descriptor.value = function (...args: any[]) {<br>    const subscription = originalMethod.apply(this, args).subscribe();<br>    if (this._subscriptions.has(key)) {<br>      this._subscriptions.get(key).unsubscribe();<br>    }<br>    this._subscriptions.set(key, subscription);<br>  };<br>  if (typeof target.ngOnDestroy !== &#39;function&#39;) {<br>    throw new Error(&#39;@AutoSubscribe: ngOnDestroy hook not provided. Please implement your class from AutoUnSubscribe&#39;);<br>  }<br>  if (!target._subscriptionsOnDestroyRegistered) {<br>    target.ngOnDestroy = function (...args: any[]) {<br>      Array.from((this._subscriptions as Map&lt;string, Subscription&gt;).entries()).forEach(([mapKey, sub]) =&gt; {<br>        sub.unsubscribe();<br>        (this._subscriptions as Map&lt;string, Subscription&gt;).delete(mapKey);<br>      });<br>      originalOnDestroy.apply(this, args);<br>    };<br>    target._subscriptionsOnDestroyRegistered = true;<br>  }<br>}</pre><pre>export type AutoUnsubscribe = OnDestroy;</pre><p>Example of usage</p><pre>@Directive()<br>export class MyDirective implements AutoUnsubscribe {<br>  public ngOnDestroy(): void {}<br><br>  @AutoSubscribe<br>  public myMethod(): Observable&lt;any&gt; {<br>    return of();<br>  }<br>}</pre><h4>How it works</h4><p>We created the decorator which modifies the original method: it will subscribe returned Observable and push to general subscriptions map-storage. Each storage item has a unique key(unique class method name).</p><p>Also, this decorator will extend onDestroy hook method: it will unsubscribe from all active subscriptions and call original onDestroy hook function.</p><p>But only one moment: Angular <strong>requires </strong>any hooks declaration directly as a component class method. So we must create theAutoUnsubscribe type which will require OnDestroy hook.</p><p>That’s all! Thank you for reading.</p><p>If you like any of the work and if it had any value to you, do please consider buying me a coffee. It makes me happy and allows me to keep creating. <a href="https://www.patreon.com/vicev">https://www.patreon.com/vicev</a></p><p>Our telegram channel: <a href="https://t.me/frontend_html_css_js">https://t.me/frontend_html_css_js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e78047856a73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/angular-auto-unsubscribe-for-rxjs-e78047856a73">Angular – Auto-unsubscribe for RxJS</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flexible entities with class-transformer]]></title>
            <link>https://medium.com/js-dojo/flexible-entities-with-class-transformer-7f4f0fc43289?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f4f0fc43289</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 20:08:06 GMT</pubDate>
            <atom:updated>2021-09-28T08:55:16.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpofnCw46zZIuJ-ex0FILg.jpeg" /></figure><p>Hello dear readers!</p><h4>Introduction</h4><p>Each developer worked, working or will work with API for getting remote data. These data returns as some kind of models, entities or format. But We often have a lot of problems with data format and code case.</p><h4>Problems</h4><p>For example let’s make request to TMDB to get latest movie(<a href="https://developers.themoviedb.org/">https://developers.themoviedb.org/</a>):</p><pre>{<br>  &quot;title&quot;: &quot;Movie name&quot;,<br>  &quot;overview&quot;: &quot;Movie overview&quot;,  <br>  &quot;release_date&quot;: &quot;2020-11-02&quot;,<br>  &quot;adult&quot;: false,<br>  &quot;runtime&quot;: 5400<br>}</pre><p>Next We could use simple JavaScript object or class instance for storing data.</p><pre>const response = await axios.get(<br>  &#39;https://api.themoviedb.org/3/movie/latest&#39;,<br>  ...<br>)<br>const data = response.data;</pre><pre>// or</pre><pre>class LatestMovie {<br>  // Properties<br>  <br>  constructor(params) {<br>    // Init properties from params<br>  }<br>}</pre><p>But both cases has problems:</p><ol><li>Simple JavaScript object don’t give any information about stored data and force us to work with snake_case code(No JS way);</li><li>Class description has a lot of boilerplate code(describing properties and initialization in constructor and also working with snake_case code in constructor);</li></ol><h4>Solution</h4><p>We could to solve this problem fast and painless with <a href="https://github.com/typestack/class-transformer">class-transformer</a>. This package gives us instrument for declarative classes describing, changing property names and properties transformation at init of class instance. So now We could rewrite our data class as:</p><pre>import { Expose, Type, Transform, plainToClass } from &#39;class-transformer&#39;;</pre><pre>class LatestMovie {<br>  @Expose()<br>  public title: string;<br>  <br>  @Expose()<br>  public overview: string;</pre><pre>  @Expose({ name: &#39;release_date&#39;)<br>  @Type(() =&gt; Date) <br>  public releaseDate: Date;</pre><pre>  @Expose({ name: &#39;adult&#39; })<br>  public isAdult: boolean;</pre><pre>  @Expose()<br>  @Transform(value =&gt; `${value / 60} minutes`, { toClassOnly: true })<br>  public runtime: string;<br>}</pre><pre>const response = await axios.get(<br>  &#39;https://api.themoviedb.org/3/movie/latest&#39;,<br>  ...<br>)<br>const latestMovie = plainToClass(LatestMovie, response.data);</pre><p>As you can see We shouldn’t write constructor and describe properties. Class-transformer do it itself with decorators:</p><ol><li>@Expose mark property as transformable;</li><li>@Type describes type of property(it could be built-in package types or another class-transformer class);</li><li>@Transform describes custom value transformation;</li><li>plainToClass(Class, data) set data to class properties.</li></ol><h4><strong>Generalization</strong></h4><p>Writing and importing plainToClass function each time may be not convenient. Let’s make code more flexible an generic:</p><pre>// axios.ts</pre><pre>import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from &#39;axios&#39;;<br>import { plainToClass, plainToClassFromExist } from &#39;class-transformer&#39;;</pre><pre>function createAxiosInstance(): AxiosInstance {<br>  return Axios.create({<br>    baseURL: process.env.apiUrl,<br>    responseType: &#39;json&#39;,<br>    validateStatus(status) {<br>      return [200].includes(status)<br>    },<br>  })<br>}<br><br>export const axiosInstance: AxiosInstance = createAxiosInstance;</pre><pre>export async function request&lt;T&gt;(config: AxiosRequestConfig, Model: any): Promise&lt;T&gt; {<br>  const response = await axiosInstance.request&lt;T&gt;(config);<br>  return plainToClass&lt;T, AxiosResponse[&#39;data&#39;]&gt;(Model, response.data);<br>}</pre><p>Now we can use it as:</p><pre>const movie = await request&lt;LatestMovie&gt;({<br>  method: &#39;get&#39;,<br>  url: &#39;https://api.themoviedb.org/3/movie/latest&#39;,<br>}, LatestMovie);</pre><p>And movie object will instance of model class. That’s all!</p><h4>Conclusion</h4><p>Class-transformer gives us declarative functionality for describing models that We should transform before using. Also one model may be as property of another model and one model may extends another model. So We have JavaScript class that transform properties before using.</p><p>Thanks for reading!</p><p>Our telegram channel: <a href="https://t.me/frontend_html_css_js">https://t.me/frontend_html_css_js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4f0fc43289" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/flexible-entities-with-class-transformer-7f4f0fc43289">Flexible entities with class-transformer</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js — Global errors handling]]></title>
            <link>https://medium.com/js-dojo/vue-js-global-errors-handling-c58aac8aaf0f?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58aac8aaf0f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Fri, 17 May 2019 12:17:40 GMT</pubDate>
            <atom:updated>2021-09-28T08:55:31.441Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Vue.js — Global errors handling</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMfrqFMfpaTH_RMvI_RQA.jpeg" /></figure><p>Errors are the most popular things that would happen with any programmer. From large and scalable to simple application — all of them have potentially errors. You should to spend a lot of time to find and fix them. If you have a project dure long time you couldn’t intercept all errors. Next we will write simple and useful global errors handler and each developer could use it individual.</p><h3>Theory</h3><p>Need to create service that will be active since before Vue startup to closing of page. So need to use Singleton pattern for this service. It means only one instance of service will be available in application. Also need to use this pattern because application shouldn’t have any collisions while errors will process.</p><p>Errors processing — storing them in separated service for developers. Need to write interface which could stream errors to this service. As separated service would be sentry.io or another own server. Our task is just stream errors to server without losts.</p><h3>Create application</h3><p>As application template choose my own based on typescript + decorators components(link to template).</p><ul><li><em>Also you could to translate code into JavaScript ES6. It will work like in TypeScript</em></li></ul><h3>Coding</h3><h4>Create service</h4><p>Let’s start from JavaScript-class based on singleton pattern. We will use one of the most popular method.</p><pre>export class ErrorsService {<br>  private static shared = new ErrorsService();<br>  <br>  static get instance() {<br>    return this.shared;<br>  }</pre><pre>  constructor() {<br>  }<br>}</pre><p>Next need to write some stream for errors. For this functional I will use rx.js. You could use something different. It doesn&#39;t matters.</p><pre>export class ErrorsService {<br>  private static shared = new ErrorsService();<br>  <br>  public errors$: Observable&lt;Error&gt;;<br>  private errorsStream$ = new ReplaySubject&lt;Error&gt;(1);</pre><pre>  public static get instance() {<br>    return this.shared;<br>  }</pre><pre>  constructor() { <br>    this.errors$ = this.errorsStream$.asObservable(); <br>  }<br>}</pre><ul><li><em>Note: It’s very important to separate Observer and Observable because need protect any pushs to stream.</em></li></ul><p>Next need write errors handler function which will push them to stream.</p><pre>public onError(error: Error) {<br>  this.errorsStream$.next(error);<br>}</pre><pre>private initHandler() {<br>  const scope = this;<br>  window.onerror = (message: Event | string, url?: string, lineNo?: number, columnNo?: number, error?: Error) =&gt; {<br>    if (error) scope.onError(error);<br>  };<br>}</pre><p>Now We have the two functions. First function “On Error” get error and push it to stream. Also this function will contain some rules for errors(It will written next). Second function “initHandler” add “error” window event listener which will intercept almost all errors in application.</p><ul><li><em>Note: window.onerror doesn&#39;t intercepts all errors. So sometimes need to push errors to service manually.</em></li></ul><h4>Handle Vue.js errors</h4><p>Window errors handling doesn’t provide Vue.js errors(e.g. errors when component mounts) handling. So need to tell Vue.js — how to process errors. Open main.ts file and write next:</p><pre>Vue.config.errorHandler = (error) =&gt; ErrorsService.<em>getInstance</em>.onError(error);</pre><h4>Handle http errors</h4><p>Part of http errors doesn&#39;t mean something bad. For example 400 status which usually uses in POST methods means wrong filled data and service shouldn’t send them to server. So need to skip all http error-statuses in handler. It’s all statuses between 400 and 404(<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">proof</a>). In my opinion another 4xx statuses should be as error. E.g. axios handling:</p><pre>onError(error: Error) {<br>  const response = (error as AxiosError).response;<br>  if (response &amp;&amp; response.status &gt;= 400 &amp;&amp; response.status &lt; 405) {<br>    return false;<br>  }<br>  this.errorsStream$.next(error);<br>}</pre><h4>Send errors to server</h4><p>This part is individual for developer because You could upload it whenever You want. I prefer upload them each time when error will pushed to stream.</p><pre>// App.ts</pre><pre>...</pre><pre>mounted() {<br>ErrorsService.errors$<br>  .pipe(flatMap(error =&gt; httpClient.post(&#39;/somepath&#39;, error)))<br>  .subscribe();<br>}</pre><pre>...</pre><h3>Conclusion</h3><p>We have the service which could handle manual, window and Vue.js errors, filter them and send to server. Thoughts about increase performance and usability: use Worker for separeted stream on OS-level, use ServiceWorker for handling push notification errors.</p><p>Thank you for reading!</p><p>Our telegram channel: <a href="https://t.me/frontend_html_css_js">https://t.me/frontend_html_css_js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58aac8aaf0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/vue-js-global-errors-handling-c58aac8aaf0f">Vue.js — Global errors handling</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js — components based on decorators with TypeScript]]></title>
            <link>https://medium.com/js-dojo/vue-js-components-based-on-decorators-with-typescript-13e89f626336?source=rss-962eedb6d022------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e89f626336</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ildar Timerbaev]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 09:27:30 GMT</pubDate>
            <atom:updated>2021-09-28T08:54:33.853Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Vue.js — components based on decorators with TypeScript</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGWdNAWvzjr6Se0omW1fEw.jpeg" /></figure><p>Hello! Before I will describe about migrating to TypeScript with decorators based components I want to tell about the reason for preparing this material. My first frontend framework is Angular 4 and after a long time working on it, of course, I got used to decorators based programming method. At start of this year I had to migrate to Vue.js and start to write a large enough application. I had a lot of components with long templates and scripts and I wanted to try to divide template, script and style to different files and start to use decorators for Object Oriented Programming paradigm. This article will very helpful for migrating from Angular to Vue.js.</p><h3>Create application</h3><p>For the first need to initialise our application with standard vue tool. It gives to us a lot of settings without writing code and manuals learning. You can skip preparing step and initialise application yourself, but it may not work. Let’s create an application.</p><pre>vue create myapp</pre><p>After run command above need to choose “select manually features”, because you didn’t have required preset yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phzpYKXzi_Wufi2Z0AykGQ.png" /></figure><p>In the next window We should select Babel, TypeScript and Linter. Also you can select other features, but there are not necessary in this step.</p><p>Next shouldn’t select class-style component syntax because will add another packages exactly for TypeScript later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTDmypkQzCE_J8-zN5RO0w.png" /></figure><p>Also auto-detected polyfills not necessary for this app. You could setup it as you like. The next step is linter selection. As applications uses TypeScript need to select TSLint. And next features is not necessary — you can setup it as you like.</p><h3>Setup application</h3><p>After successful application initialisation need to install two packages:</p><pre>npm i vue-class-component vue-property-decorator</pre><p>First package gives class based component and second package gives decorators for all vue.js key features, like props, watchers, emitter etc. After successfully installation We could create components based on classes and decorators with divided files. Let’s do it!</p><pre>$ mkdir ./components/hello<br>$ touch hello.component.html hello.component.ts hello.component.vue hello.component.css</pre><p>In this moment I suggest to use schematics or something like it for generating this files automatically. Let’s open hello.component.vue file and write there next:</p><pre>&lt;template src=“./hello.component.html”&gt;&lt;/template&gt;<br>&lt;script src=“./hello.component.ts” lang=“ts”&gt;&lt;/script&gt;<br>&lt;style src=“./hello.component.css” lang=“css” scoped&gt;&lt;/style&gt;</pre><p>Now, we have a few important moments: all paths should be relative by current directory, script and style tags should have lang attribute: it need for detection which language is uses. Next, open the hello.component.ts file and write next:</p><pre>import { Component, Vue } from ‘vue-property-decorator’;</pre><pre>@Component<br>export default class HelloComponent extends Vue { }</pre><p>And that’s all! After these steps you could to use components based on decorators. This method of using Vue.js is helpful for a complex projects with a lot of components, because you can write code with Object Oriented Programming method and call Vue features with decorators. Also extending Vue class gives the scope of component: e.g. you could call router also as before:</p><pre>this.$router</pre><p>Decorators based components doesn’t mean that you couldn’t use native vue components — you could use also as before.</p><p>Thank you for reading!</p><p>Completed application you would find here: <a href="https://github.com/dkildar/vuejs-typescript-initial">https://github.com/dkildar/vuejs-typescript-initial</a></p><p>Vue class component: <a href="https://github.com/vuejs/vue-class-component">https://github.com/vuejs/vue-class-component</a></p><p>Vue property decorator: <a href="https://github.com/kaorun343/vue-property-decorator">https://github.com/kaorun343/vue-property-decorator</a></p><p>Our telegram channel: <a href="https://t.me/frontend_html_css_js">https://t.me/frontend_html_css_js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e89f626336" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/vue-js-components-based-on-decorators-with-typescript-13e89f626336">Vue.js — components based on decorators with TypeScript</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>