<?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 Khaled Osman on Medium]]></title>
        <description><![CDATA[Stories by Khaled Osman on Medium]]></description>
        <link>https://medium.com/@khaledosman?source=rss-5c34e1116828------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*01RPYNst1D5svgX0oAoahw.jpeg</url>
            <title>Stories by Khaled Osman on Medium</title>
            <link>https://medium.com/@khaledosman?source=rss-5c34e1116828------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:58:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khaledosman/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[How to optimize a serverless typescript eslint webpack setup for performance]]></title>
            <link>https://itnext.io/how-to-optimise-your-serverless-typescript-webpack-eslint-setup-for-performance-86d052284505?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d052284505</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 12:11:08 GMT</pubDate>
            <atom:updated>2021-11-22T13:51:35.178Z</atom:updated>
            <content:encoded><![CDATA[<p>Or how I improved the Serverless AWS NodeJS Typescript template (<a href="https://github.com/serverless/serverless/tree/master/lib/plugins/create/templates/aws-nodejs-typescript">aws-nodejs-typescript</a>) in terms of both build time as well as bundle size by tweaking the typescript setup, webpack, serverless.yml and eslint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDyJpHrHPbjP7Fm-rPFtUg.png" /></figure><p>If your typescript, eslint or webpack setup is slow, you can follow the tips below to optimise them.</p><h4>Optimising Typescript — tsconfig.json</h4><ol><li>Include **/*.ts files only and Exclude node_modules and build directories.</li><li>Remove comments from the bundle by setting “removeComments”: true under compilerOptions .</li><li>Enable the incremental and watch APIs.</li></ol><pre>// tsconfig.json<br><strong><br></strong>{</pre><pre>  &quot;compilerOptions&quot;: {</pre><pre>  &quot;lib&quot;: [</pre><pre>    &quot;es2017&quot;</pre><pre>  ],</pre><pre>  &quot;removeComments&quot;: true,</pre><pre>  &quot;moduleResolution&quot;: &quot;node&quot;,</pre><pre>  &quot;resolveJsonModule&quot;: true,</pre><pre>  &quot;noUnusedLocals&quot;: false,</pre><pre>  &quot;noUnusedParameters&quot;: false,</pre><pre>  &quot;sourceMap&quot;: true,</pre><pre>  &quot;allowSyntheticDefaultImports&quot;: true,</pre><pre>  &quot;forceConsistentCasingInFileNames&quot;: true,</pre><pre>  &quot;importHelpers&quot;: true,</pre><pre>  &quot;incremental&quot;: true,</pre><pre>  &quot;watch&quot;: true,</pre><pre>  &quot;target&quot;: &quot;es2017&quot;,</pre><pre>  &quot;outDir&quot;: &quot;lib&quot;</pre><pre>},</pre><pre>&quot;include&quot;: [</pre><pre>  &quot;./**/*.ts&quot;</pre><pre>],</pre><pre>&quot;exclude&quot;: [</pre><pre>  &quot;node_modules/**/*&quot;,</pre><pre>  &quot;.serverless/**/*&quot;,</pre><pre>  &quot;.webpack/**/*&quot;,</pre><pre>  &quot;_warmup/**/*&quot;,</pre><pre>  &quot;.vscode/**/*&quot;,</pre><pre>  &quot;*.config.js&quot;,</pre><pre>  &quot;**/*.js&quot;</pre><pre> ]</pre><pre>}</pre><h4>Optimising eslint — .eslintrc.js</h4><p>Now that <a href="https://github.com/palantir/tslint/issues/4534">tslint is deprecated</a> we should use eslint with <a href="https://github.com/typescript-eslint/typescript-eslint/">typescript-eslint</a> instead. However I couldn’t help but notice the performance difference after switching, eslint was slower than tslint out of the box. Here’s what you can do to get the most out of it:</p><ol><li>Setup an .eslintignore file to ignore node_modules as well as build / non-typescript files.</li><li>Use the --cache flag when running eslint, example: eslint --cache **/*.ts .</li><li>Don’t extend the expensive &quot;plugin:@typescript-eslint/recommended-requiring-type-checking&quot; configuration in your eslint config.</li><li>Add an .eslintignore file to ignore node_modules and build directories</li></ol><pre>//.eslintrc.js<br>module.exports = {</pre><pre>&quot;extends&quot;: [</pre><pre>  &quot;eslint:recommended&quot;,</pre><pre>  &quot;plugin:@typescript-eslint/eslint-recommended&quot;,</pre><pre>  &quot;plugin:@typescript-eslint/recommended&quot;,</pre><pre>  &quot;standard&quot;</pre><pre>],</pre><pre>&quot;env&quot;: {</pre><pre>  &quot;node&quot;: true</pre><pre>},</pre><pre>&quot;parser&quot;: &quot;@typescript-eslint/parser&quot;,</pre><pre>&quot;plugins&quot;: [</pre><pre>  &quot;@typescript-eslint&quot;,</pre><pre>],</pre><pre>&quot;settings&quot;: {</pre><pre>  &quot;import/parsers&quot;: {</pre><pre>    &quot;@typescript-eslint/parser&quot;: [</pre><pre>    &quot;.ts&quot;,</pre><pre>    &quot;.tsx&quot;</pre><pre>  ]</pre><pre>  },</pre><pre>  &quot;import/resolver&quot;: {</pre><pre>    &quot;typescript&quot;: {} </pre><pre>  }</pre><pre>},</pre><pre>&quot;parserOptions&quot;: {</pre><pre>  &quot;project&quot;: &quot;./tsconfig.json&quot;,</pre><pre>  &quot;tsconfigRootDir&quot;: &quot;./&quot;,</pre><pre>  &quot;sourceType&quot;: &quot;module&quot;,</pre><pre>  &quot;ecmaVersion&quot;: 2018</pre><pre>},</pre><pre>&quot;rules&quot;: {</pre><pre>  &quot;@typescript-eslint/no-explicit-any&quot;: &quot;off&quot;,</pre><pre>  }</pre><pre>}</pre><p>Add an .eslintignore file to ignore non src files that do not need to be linted</p><pre>//.eslintignore<br>node_modules</pre><pre>.serverless</pre><pre>.vscode</pre><pre>*.config.js</pre><pre>.webpack</pre><pre>_warmup</pre><pre>**/*.js</pre><h4>Optimising webpack.config.js</h4><ol><li>Install <a href="https://github.com/liady/webpack-node-externals">webpack-node-externals</a> to remove unused node_modules from the build.</li><li>Set the devtool to cheap-module-eval-source-map for development/local builds.</li><li>Remove unnecessary extensions from your “resolve” property.</li><li>Exclude node_modules as well as build / non-src directories from your loader rules.</li><li>Optimise your webpack build performance via <a href="https://webpack.js.org/guides/build-performance/">these tips</a>.</li><li>Disable type-checking from ts-loader and enable the new watch API.</li><li>Use <a href="https://www.npmjs.com/package/fork-ts-checker-webpack-plugin">fork-ts-webpack-checker-plugin</a> to run type-checking on a separate process.</li></ol><pre>// webpack.config.js<br>const path = require(&#39;path&#39;);<br>const slsw = require(&#39;serverless-webpack&#39;);<br>const nodeExternals = require(&#39;webpack-node-externals&#39;);<br>const ForkTsCheckerWebpackPlugin = require(&#39;fork-ts-checker-webpack-plugin&#39;);<br><br>module.exports = {<br>  context: __dirname,<br>  mode: slsw.lib.webpack.isLocal ? &#39;development&#39; : &#39;production&#39;,<br>  entry: slsw.lib.entries,<br>  devtool: slsw.lib.webpack.isLocal ? &#39;cheap-module-eval-source-map&#39; : &#39;source-map&#39;,<br>  resolve: {<br>    extensions: [&#39;.mjs&#39;, &#39;.json&#39;, &#39;.ts&#39;],<br>    symlinks: false,<br>    cacheWithContext: false,<br>  },<br>  output: {<br>    libraryTarget: &#39;commonjs&#39;,<br>    path: path.join(__dirname, &#39;.webpack&#39;),<br>    filename: &#39;[name].js&#39;,<br>  },<br>  target: &#39;node&#39;,<br>  externals: [nodeExternals()],<br>  module: {<br>    rules: [<br>      // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`<br>      {<br>        test: /\.(tsx?)$/,<br>        loader: &#39;ts-loader&#39;,<br>        exclude: [<br>          [<br>            path.resolve(__dirname, &#39;node_modules&#39;),<br>            path.resolve(__dirname, &#39;.serverless&#39;),<br>            path.resolve(__dirname, &#39;.webpack&#39;),<br>          ],<br>        ],<br>        options: {<br>          transpileOnly: true,<br>          experimentalWatchApi: true,<br>        },<br>      },<br>    ],<br>  },<br>  plugins: [<br>    // new ForkTsCheckerWebpackPlugin({<br>    //   eslint: true,<br>    //   eslintOptions: {<br>    //     cache: true<br>    //   }<br>    // })<br>  ],<br>};</pre><p>8. (Bonus) Upgrade to webpack v5 <a href="https://webpack.js.org/migrate/5/">https://webpack.js.org/migrate/5/</a></p><h4>Optimising serverless.yml</h4><ol><li>In order to setup node-externals correctly with serverless-webpack plugin you need to set custom: webpack: includeModules option in your serverless.yml file as mentioned <a href="https://github.com/serverless-heaven/serverless-webpack#node-modules--externals">here by the serverless-webpack plugin</a> in order to properly support the <a href="https://github.com/liady/webpack-node-externals">webpack node externals plugin</a></li><li>Enable GZip compression to minimise returned response size by setting apiGateway:minimumCompressionSize: 1024 in the serverless.yml file</li><li>Enable AWS connection reuse by setting environment: AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1 to <a href="https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html">reuse HTTP connections</a></li></ol><pre>//serverless.yml<br>service:<br>  name: aws-nodejs-typescript<br># app and org for use with dashboard.serverless.com<br>#app: your-app-name<br>#org: your-org-name<br><br>custom:<br>  webpack:<br>    webpackConfig: ./webpack.config.js<br>    includeModules: true<br><br># Add the serverless-webpack plugin<br>plugins:<br>  - serverless-webpack<br><br>provider:<br>  name: aws<br>  runtime: nodejs10.x<br>  apiGateway:<br>    minimumCompressionSize: 1024 # Enable gzip compression for responses &gt; 1 KB<br>  environment:<br>    AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1<br><br>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - http:<br>          method: get<br>          path: hello</pre><h4>Results:</h4><p>Now lets take a look at the results after implementing the above optimisations. Thanks to github user <a href="https://github.com/sapher"><em>sapher</em></a> for providing his own feedback on a big project after my <a href="https://github.com/serverless/serverless/pull/6904">pull request</a>. These are his results</p><p>Before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*ni8umos4z7BIVFaDfmUbGQ.png" /></figure><p>After:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*2wpGDwNrSImtCTWaGAgdZw.png" /></figure><p>As you can see that’s a <strong>37 000%</strong> file size difference from <strong>5.9MB</strong> to <strong>13.8 KB </strong>for the first file, and a <strong>3410%</strong> build speed increase (from <strong>45.5 seconds</strong> to <strong>1.3 seconds</strong>!).</p><p>And these are the results in the template hello world project with no dependencies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*fF9ouBa_HltXHZaB3r6BMg.png" /></figure><p><strong>I made a </strong><a href="https://github.com/serverless/serverless/pull/6904"><strong>pull request here</strong></a><strong> with these changes to the </strong><a href="https://github.com/serverless/serverless"><strong>serverless repository</strong></a><strong> that was already merged in November 2019.</strong></p><p>If your project was created earlier you might want to update your setup manually by looking at the changes in the pull request, they’re actually very small, but quite significant as you can see.</p><h4>Optimising total package size &amp; Deployment speed</h4><p>I was later able to cut my packaged zip files by more than half and speed up my packaging and deployments by:</p><ol><li><a href="https://webpack.js.org/migrate/5/#upgrade-webpack-cli-to-the-latest-available-version-when-used">updating to webpack v5</a></li><li>use <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html">s3 transfer acceleration </a>by using the aws-s3-accelerate flag when running sls deploy for faster uploads to s3 at additional costs.</li><li>switching from npm to yarn to make use of the <a href="https://yarnpkg.com/en/docs/cli/autoclean">autoclean</a> feature by running yarn autoclean — initand yarn autoclean — force which cleans up my node_modules and removes unnecessary files from there thanks to this <a href="https://github.com/serverless-heaven/serverless-webpack/issues/519">github issue</a> in serverless-webpack.</li><li>Configuring serverless-webpack plugin to use yarn autoclean for the included node_modules and using my configured .yarnclean file by adding this to my serverless.yml</li></ol><pre>//serverless.yml<br>webpack:</pre><pre>webpackConfig: ./webpack.config.js</pre><pre>includeModules: true</pre><pre>forceExclude:</pre><pre>- aws-sdk</pre><pre>packager: &quot;yarn&quot;</pre><pre>packagerOptions:</pre><pre>scripts:</pre><pre>- yarn autoclean --init</pre><pre>- rm .yarnclean &amp;&amp; cat ../../.yarnclean &gt;&gt; .yarnclean &amp;&amp; echo &#39;\n*.ts&#39; &gt;&gt; .yarnclean</pre><pre>- rm -rf node_modules/aws-sdk</pre><pre>- yarn autoclean --force</pre><p>6. Configuring a <a href="https://gist.github.com/khaledosman/e145fffc2de691e780c7da246e2b3da4">more advanced </a><a href="https://gist.github.com/khaledosman/e145fffc2de691e780c7da246e2b3da4">.yarnclean</a> file than that created via yarn autoclean — init which also uses files deleted by <a href="https://github.com/tj/node-prune">node-prune</a></p><p>7. Forcefully removing aws-sdk from my packages via serverless-webpack’s packagerOptions.scripts I noticed that even though the aws-sdk was stated as a devDependency and was being excluded by externals pugin, it was still being added in my packages through aws-xray-sdk-core which states aws-sdk as a dependency instead of a peerDependency so it still ended up in my package, there’s already a <a href="https://github.com/aws/aws-xray-sdk-node/issues/113">github issue</a> for this in aws-xray-sdk.</p><p>The above steps helped reduced the package size for one of my lambdas from <strong>18MB</strong> all the way down to <strong>7MB </strong>and others from <strong>11MB</strong> to <strong>2.7MB.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d052284505" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-optimise-your-serverless-typescript-webpack-eslint-setup-for-performance-86d052284505">How to optimize a serverless typescript eslint webpack setup for performance</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL performance tip: Select fields from requests all the way from the database]]></title>
            <link>https://itnext.io/graphql-performance-tip-database-projection-82795e434b44?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/82795e434b44</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 10:35:06 GMT</pubDate>
            <atom:updated>2021-07-07T15:13:50.299Z</atom:updated>
            <content:encoded><![CDATA[<p>The real power of GraphQL.. Specifying the requested fields from the client request all the way down to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaVM-IJvQiWFEEscw2eIrg.png" /></figure><h4>The problem</h4><p>One of the most powerful features of GraphQL is the ability for the client to specify the fields returned from the response so that less data is shipped across the network and thus avoiding over-fetching data.</p><p>However, are we really doing less work? The backend server and the database still have to do all the work of querying the database, getting all the fields of the requested object(s), and then only return the requested fields through the GraphQL/Network layer.</p><p>So we’re only saving network time by shipping a smaller response size, but our backend server and the database are still doing the extra unnecessary work to get all the fields of the requested objects. This is essentially a lot of time wasted that we could potentially optimise.</p><h4>Solution</h4><p>What if there was a way to figure out which fields were requested by the client and return only these fields from the database layer?</p><p>Most modern database offer a “projection” or a “selection” feature where the database driver allows the consumer to specify which fields should be returned from the documents that match the database query in order to avoid returning all the unnecessary ones and speed up queries to the database.</p><p>This has a quite significant impact on the database query performance as it avoid unnecessary work, if you’re curious what the potential savings might look like, take a look at <a href="https://medium.com/faun/performance-tips-for-mongodb-mongoose-190732a5d382">this article</a> I wrote earlier which showcases some performance metrics with/without projection in MongoDB.</p><p><a href="https://medium.com/faun/performance-tips-for-mongodb-mongoose-190732a5d382">How to optimize MongoDB &amp; Mongoose for Performance</a></p><h4>Apollo-Server’s resolver function</h4><p>So we have the possibility to do this from the Network layer as well as the database layer, the only thing missing is to figure it out in our server/resolver.</p><p>A graphQL resolver function written in <a href="https://github.com/apollographql/apollo-server">apollo-server</a> usually takes four input params. root, args, context and info . If we were to write a resolver that returns all users from the database for example it would look like this:</p><pre>resolvers = {</pre><pre>  getUsers: function (root, args, context, info) {<br>    const User = mongoose.model(&#39;User&#39;)</pre><pre>    return User.find({})</pre><pre>  }</pre><pre>}</pre><p>The root object is usually the parent object of this requested operation/field in the Schema. args is whatever arguments may be passed to that operation, and context includes whatever you pass into your context object (usually used for authentication). However what about the info object? it seems to include some info about the incoming request.</p><p>So I looked up its documentation in <a href="http://apollographql.com/">apollographql.com</a> and this is what I found</p><blockquote>Info: This argument should only be used in advanced cases, but it contains information about the execution state of the query, including the field name, path to the field from the root, and more. It’s only documented in the GraphQL.js source code.</blockquote><p>Not very helpful, but I figured it might include the needed information about the incoming request and the requested fields, After looking at online libraries that might be able to do what I want and I found graphql-fields.</p><h4>graphql-fields</h4><p>I came across <a href="https://github.com/robrichard/graphql-fields">graphql-fields</a> which can return the requested fields based on the info param, it also works with advanced cases like union types, fragments, sub-fields, etc..</p><p>Here’s what it can do, for a query like this that returns all users’ names and emails</p><pre>{</pre><pre>  users {</pre><pre>    name</pre><pre>    email</pre><pre>  }</pre><pre>}</pre><p>This would be the result: [‘name’, ‘email’]</p><p><strong>Usage:</strong></p><pre>const graphqlFields = require(‘graphql-fields’);<br>function userResolver(root, args, context, info) {</pre><pre>  const topLevelFields = Object.keys(graphqlFields(info));<br>  console.log(topLevelFields)<br>  // prints [‘name’, ‘email’]<br>}</pre><p>Great, now we can use this result to select only these fields from the database instead of requesting the entire User document from the database for each user.</p><h4>Using the result</h4><p>In my case I was using MongoDB with <a href="https://github.com/Automattic/mongoose">Mongoose</a> as the database driver, so the syntax needed for mongoose projection looks a little bit different from the result I got from graphql-fields .</p><p>The equivalent query I wanted to achieve looks like the following: User.find({}).select({name: 1, email: 1}).lean()</p><p>A helper function that can transform the result coming from graphql-fields into the selection object required by mongoose can be written as follows:</p><pre>export function getMongooseSelectionFromSelectedFields (info, fieldPath = null) {</pre><pre>  const selections = graphqlFields(info)</pre><pre>  const mongooseSelection = Object<br>  .keys(fieldPath ? selections[fieldPath] : selections)<br>  .reduce((a, b) =&gt; ({ …a, [b]: 1   }), {})</pre><pre>  return mongooseSelection</pre><pre>}</pre><p>And voila, Now the fields requested by the client are the ones requested and returned from the database making our resolver a lot faster!</p><p>This works flawlessly with <a href="https://www.apollographql.com/docs/apollo-server/performance/apq/">Automatic Persisted Queries (APQ)</a> and <a href="https://www.apollographql.com/docs/apollo-server/performance/caching/">Caching</a>. Another two performance easy wins.</p><p>I added a fieldPath parameter to support one level of nesting in the response in case the operation that requests data from the database is not the top level one.</p><p>This is what the new resolver looks like:</p><pre>resolvers = {</pre><pre>  getUsers: function (root, args, context, info) {<br>    const mongooseSelection = getMongooseSelectionFromRequest(info)</pre><pre>    return User.find({}).select(mongooseSelection).lean()</pre><pre>  }</pre><pre>}</pre><h4>Conclusion</h4><p>GraphQL is quite powerful, not only does it optimise performance for client apps, but can also be used to optimise backend performance, after all we get the specifically requested fields in our resolver for free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82795e434b44" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/graphql-performance-tip-database-projection-82795e434b44">GraphQL performance tip: Select fields from requests all the way from the database</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to optimize MongoDB & Mongoose for Performance]]></title>
            <link>https://itnext.io/performance-tips-for-mongodb-mongoose-190732a5d382?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/190732a5d382</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Fri, 02 Aug 2019 12:23:03 GMT</pubDate>
            <atom:updated>2021-07-07T15:14:01.625Z</atom:updated>
            <content:encoded><![CDATA[<h4>What can you do to make your mongodb/mongoose queries faster?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*Ipg_guKJO2MwacQ_3amxGw.jpeg" /></figure><p>Performance is the art of avoiding unnecessary work. These are my findings regarding optimising MongoDB queries, you can scroll below for performance tests &amp; results.</p><h4><strong>1. Use lean queries for GET operations</strong></h4><p>This is probably the best thing you can do to improve the performance of a query. Mongoose allows you to add .lean() at the end of your queries which dramatically improves your query’s performance by returning plain JSON objects instead of Mongoose Documents.</p><p>From <a href="https://mongoosejs.com/docs/tutorials/lean.html">Mongoose docs on lean</a></p><blockquote>“By default, Mongoose queries return an instance of the <a href="https://mongoosejs.com/docs/api.html#Document">Mongoose </a><a href="https://mongoosejs.com/docs/api.html#Document">Document class</a>. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the leanoption tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.</blockquote><blockquote>The <a href="https://mongoosejs.com/docs/api.html#query_Query-lean">lean option</a> tells Mongoose to skip <a href="https://mongoosejs.com/docs/api.html#model_Model.hydrate">hydrating</a> the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), <strong>not</strong> <a href="https://mongoosejs.com/docs/documents.html">Mongoose documents</a>.”</blockquote><p>However this comes at a cost, This means that lean docs don&#39;t have:</p><ul><li>Change tracking</li><li>Casting and validation</li><li>Getters and setters</li><li>Virtuals (including “id”)</li><li>save() function</li></ul><p>So its usually optimal for GET endpoints and .find() operations that don’t use .save() or virtuals.</p><h4>2. Create custom Indexes for your queries</h4><p>MongoDB allows you to create indexes on other properties in your Schema other than the default “_id” index. That way your documents can be indexed by your defined properties in the database for faster access.</p><p>You can also create compound indexes of more than one property. This is useful if you’re querying by multiple fields. Say you have some database and you would like to find all extinct animals, you would probably write a query like so Model.find({type: “Animal”, status: “extinct&quot;})</p><p>MongoDB will have to look at all the documents to find ones that match this criteria, To optimise this query you can create a compound index for “type” and “status” by adding ModelSchema.index({type: 1, status: 1}). MongoDB will now where to look at to find relevant documents.</p><p>The “1” or “-1” indicates the sort order of the properties. The order in which the fields are added to the index is important. For a more detailed explanation about indexes see <a href="https://mongoosejs.com/docs/guide.html#indexes">https://mongoosejs.com/docs/guide.html#indexes</a> and <a href="https://docs.mongodb.com/manual/indexes/">https://docs.mongodb.com/manual/indexes/</a></p><h4>3. Minimise DB requests (avoid .populate() if possible)</h4><p>The more requests you do the slower your app response time becomes. Try to minimise your database queries as much as possible and combine them together or ideally avoiding them at all by getting rid of duplicate or unnecessary db operations. You can also cache your database results in <a href="https://redis.io/">redis</a>.</p><p>Try to define your schemas in a way such that you don’t have to rely much on .populate() and bidirectional relations between models. Because that’s where NoSQL databases aren’t very ideal. Every property you add in your model will be returned from your queries, so if you have an array or a nested object in some of these fields, your document will easily get huge slowing down the performance of your query.</p><p>If your document includes an array of references to other Models, and you use .populate() to join data between collections, using .populate() will require running extra queries to fetch the actual documents inside that array for you, so its similar to running an extra query for each id for each document. Its better to favour using .aggregate() instead of .populate() if your really have to.</p><h4>4. Use .select() to select specific properties to return</h4><p>When querying the database for documents, the query will return you the entire document, but sometimes you have large documents with lots of fields and fields that are arrays/objects as explained above and you don’t really need to use all the returned properties.</p><p>To prevent the database from doing extra work to return these fields increasing the size of the returned documents you can use mongoose .select() to include/exclude the fields you want your query to return specifically as follows:</p><pre>Model.find({type: &quot;Animal&quot;}).select({name: 1})</pre><p>Protip: This works really well if you’re using GraphQL, so you know what fields exactly the client requested and can select these fields from the database. I wrote another article about this here</p><p><a href="https://medium.com/faun/graphql-performance-tip-database-projection-82795e434b44">GraphQL performance tip: Select fields from requests all the way from the database</a></p><h4>5. Run db operations in parallel</h4><p>A common mistake I see in NodeJS code whenever people use async/await is that people run operations one after the other when they don’t need to be. For example:</p><pre>const user = new User({name: &quot;bob&quot;})<br>const post = new Post({title: &quot;hello&quot;})</pre><pre>await user.save()<br>await post.save()</pre><p>There’s no reason to wait until the user is saved in order to save the post. Instead, the database operations can be run in parallel using Promise.all as follows:</p><pre>const [user, post] = await Promise.all([user.save(), post.save()])</pre><p>While this may improve the performance on the api level, we’re still doing two requests to the database, so its even better to use insertMany() orbulkWrite() if you want to do multiple operations as a batch.</p><h4>6. Cache/reuse mongoose connections</h4><p>Make sure you don’t connect and disconnect from the database every time you want to insert/query something from the database or every-time your endpoint is triggered. Instead you should connect once at the beginning of your app and reuse the connection.</p><p>This is because setting up a new TCP connection is expensive time-wise, network request wise and memory wise, Also a new connection means a new thread to be created by MongoDB using memory on the database as well.</p><h3>Lets write some performance tests to see the results</h3><p>How much can these tips improve your query performance? Let’s try it out by writing some script to test the differences.</p><p>I ran a local installation of MongoDB and wrote a NodeJS script that populates the database with a list of randomly generated users thanks to <a href="https://github.com/boo1ean/casual">casual</a>. The goal is to find users who are older than 22 years old.</p><p>I wrote the query in different ways combining the methods mentioned above and tried them on two different database collections that are populated with the same dataset. One collection had an index on the “age” property while the other did not. The results were measured using the console.time() API and the tests were run using the latest current versions of NodeJS (v12.7.0)and mongoose (v5.6.7).</p><p>First lets start with out Schema, here I define to user collections/schemas, one has an index on the age property while the others doesn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VElBX7vztYrh2480Ux5LMw.png" /></figure><p>Now let’s write some code to populate the database with random data. I used <a href="https://github.com/boo1ean/casual">casual</a> library which is pretty handy to generate semantic mock data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66c9oPK6Dp_fRT8kebIF1g.png" /></figure><p>Now that the database is ready, Let’s write our queries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSRB1Be3MUY-BNA_HXvtvA.png" /></figure><h3>Performance Results &amp; Observations</h3><p><strong><em>With 1k users</em></strong><br>default_query: 135.646ms<br>query_with_index: 168.763ms<br>query_with_select: 27.781ms<br>query_with_select_index: 55.686ms<br>lean_query: 7.191ms<br>lean_with_index: 7.341ms<br>lean_with_select: 4.226ms<br>lean_select_index: 7.881ms</p><p><strong><em>With 10k users in the database</em></strong></p><p>default_query: 323.278ms<br>query_with_index: 355.693ms<br>query_with_select: 212.403ms<br>query_with_select_index: 183.736ms<br>lean_query: 92.935ms<br>lean_with_index: 92.755ms<br>lean_with_select: 36.175ms<br>lean_select_index: 38.456ms</p><p><strong><em>With 100K Users in the database</em></strong><br>default_query: 2425.857ms<br>query_with_index: 2371.716ms<br>query_with_select: 1580.393ms<br>query_with_select_index: 1583.015ms<br>lean_query: 858.839ms<br>lean_with_index: 944.712ms<br>lean_with_select: 383.548ms<br>lean_select_index: 458.000ms</p><p>As you can see the optimised version of the query that uses .lean() .select() and Schema.index({}) was about 10x faster than the default query, Which is a huge win!</p><p>.lean() seems to have the highest impact on performance followed by .select() , The reason my custom index didn’t help in that case was because my index was <a href="https://docs.mongodb.com/manual/tutorial/create-queries-that-ensure-selectivity">not selective enough</a> since it only decreases the number of scanned documents by 50%.</p><p>You can find the script used for these tests and you can even try it out yourself <a href="https://github.com/khaledosman/mongo-performance-expirements">here</a> <a href="https://github.com/khaledosman/mongo-performance-expirements">https://github.com/khaledosman/mongo-performance-expirements</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190732a5d382" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/performance-tips-for-mongodb-mongoose-190732a5d382">How to optimize MongoDB &amp; Mongoose for Performance</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting a free private npm registry with Verdaccio]]></title>
            <link>https://itnext.io/creating-a-free-private-npm-registry-with-verdaccio-e1becdc542b?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1becdc542b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 07:56:39 GMT</pubDate>
            <atom:updated>2020-10-10T19:17:41.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a free private npm registry with Verdaccio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*he2KcGD3HnSn1bwcRFGJ3Q.png" /></figure><h3>The problem</h3><p>Sometimes you want to share code, libraries or components across your projects or organisation, but don’t want your npm packages to be public.</p><p>With npm registries you can publish your own npm packages that have their own release cycle so that anyone with access to the registry can install and use in their own projects. This helps achieve modularity, code re-usability and separation of concerns in your codebase.</p><p><a href="https://www.npmjs.com/products/enterprise">npm enterprise</a> already offers that however its not free. <a href="https://github.com/verdaccio/verdaccio">Verdaccio</a> is a lightweight private npm proxy registry that allows you to have your own npm registry for free. In the following sections I’ll walk you through how you can setup and configure your own private npm registry.</p><h3>Configuring Verdaccio</h3><ol><li>You can clone one of the example repositories <a href="https://github.com/verdaccio/docker-examples">here</a> to get started. In my case I’ll be using the “docker-local-storage-volume” one to store published packages locally on my server through a mounted docker volume.</li><li>You can change the configuration to fit your needs from the conf/config.yaml file, the <a href="https://verdaccio.org/docs/en/configuration">docs</a> include all necessary information regarding the possible configuration options.</li><li>In my case I want only authenticated users to be able to see and publish packages for security reasons, after all it should be private, right? So I’m going to follow <a href="https://verdaccio.org/docs/en/packages">this</a> to make it so users are only allowed to publish packages that have the <em>@myscope</em> scope prefix in their package name as defined in package.json. You can read more about npm scopes <a href="https://docs.npmjs.com/about-scopes">here</a> if you’re not familiar with them. its basically a way to group your packages per user/organization. So this is what my configuration will looks like</li></ol><pre>&#39;@myscope/*&#39;:<br>    # scoped packages<br>    # you can specify usernames/groupnames (depending on your auth plugin)<br>    # and three keywords: &quot;$all&quot;, &quot;$anonymous&quot;, &quot;$authenticated&quot;<br>    access: &quot;$authenticated&quot;<br>    publish: &quot;$authenticated&quot;<br>    # if package is not available locally, proxy requests to &#39;npmjs&#39; registry<br>    proxy: npmjs</pre><p>The last line makes our registry act as a proxy to the public npm registry in case a user tries to access a package that does not exist in the private registry, in which case the request will be redirected and the package will be installed from the default public npm registry. Verdaccio will also cache packages installed on the server.</p><p>4. I want to turn off user registration and only allow specific users to access the registry, otherwise any external users with access to the URL can register new accounts and be able to access or publish packages, luckily Verdaccio comes with an htpasswd plugin for authentication, the docs to setup authentication can be found <a href="https://verdaccio.org/docs/en/authentification">here</a>. This is what my setup looks like</p><pre>auth:<br>  htpasswd:<br>    file: /verdaccio/conf/htpasswd<br>    # Maximum amount of users allowed to register, defaults to &quot;+inf&quot;.<br>    # You can set this to -1 to disable registration.<br>    max_users: -1</pre><p>That’s it, now only users configured in the /verdaccio/conf/htpasswd file will be able to access the registry and registration is disabled. I will show you how you can create a new user in the next section.</p><p>5. That’s it, deploy your docker image to a server with your favorite cloud provider, but make sure to run the following commands in the deployed instance to allow writing and storing packages into the directories.</p><pre>chmod -R 777 storage/<br>chmod -R 777 conf/</pre><h3>Authentication &amp; Creating a new user</h3><p>To give a new user access to the registry you just need to add another htpasswd entry to your htpasswd file.</p><ol><li>Go to <a href="http://www.htaccesstools.com/htpasswd-generator/">http://www.htaccesstools.com/htpasswd-generator/</a></li><li>Create your username and password.</li><li>Send the generated htpasswd line and copy it into the verdaccio/conf/htpasswd file on the server.</li><li>You should now be able to login using that username and password either from the web interface or through npm.. (No server restart is required)</li></ol><h3>Publishing &amp; Installing private npm modules</h3><p>Now that we have deployed and secured our private npm registry, we just need to configure npm to use it.</p><p>Remember we will be using scoped packages as a best practice, check these links for a better understanding on <a href="https://docs.npmjs.com/misc/scope">npm scopes</a> and <a href="https://docs.npmjs.com/private-modules/intro">private modules</a>.</p><ol><li>You can set your default npm scope to @myscope. to ensure your package names start with <em>@myscope</em> when you do an npm init npm config set scope @myscope</li><li>Set your local npm registry to point to the new registry instead of the default public npm registry, otherwise you would have to specify the registry through the — -registryflag with every npm command you use. npm set registry &lt;PRIVATE_REGISTRY_URL&gt;</li><li>To register/login with your own username created from the previous section so that you can publish your own packages runnpm adduser</li><li>Once logged in, you can now publish your own npm module to the registry by running npm publish .</li><li>You can install the newly published package on that registry by running:npm install @myscope/my-first-published-package</li></ol><p>That’s it, you can now publish and install private packages securely and share modules with your coworkers or across multiple projects without having to worry about them the same way you would install any other package from npm. Verdaccio also comes with a nice web interface for your registry similar to your npm’s. You can access it from your browser through port 4783.</p><p>If you like my content and would like to support me, you can <a href="https://www.buymeacoffee.com/khaledosman">buy me a beer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1becdc542b" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-a-free-private-npm-registry-with-verdaccio-e1becdc542b">Hosting a free private npm registry with Verdaccio</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy web apps to AWS using S3 & CloudFront]]></title>
            <link>https://itnext.io/deploying-a-web-app-on-aws-using-s3-cloudfront-45f77cd652c6?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f77cd652c6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 10:15:58 GMT</pubDate>
            <atom:updated>2023-11-30T13:36:48.312Z</atom:updated>
            <content:encoded><![CDATA[<p>If you ever find yourself lost in AWS docs, you’re not alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*vb_oGv53xB5SoOg2WxAVHg.png" /></figure><p>In this article you can learn how to deploy your website and frontend applications on AWS using AWS S3, CloudFront and Route 53. We’re going to be using S3 to store our source code and assets, CloudFront as a CDN to distribute our website and provide HTTPS support, and Route53 to create a custom DNS record that points to CloudFront distribution. Lets jump right through it.</p><h4>Setting up our S3 Bucket</h4><blockquote>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. This means customers of all sizes and industries can use it to store and protect any amount of data for a range of use cases, such as websites, mobile applications, backup and restore, archive, enterprise applications, IoT devices, and big data analytics.</blockquote><p>First we need to create our s3 bucket where we’re going to store out code &amp; assets. To configure our bucket for static website hosting follow these steps:</p><ol><li>Create a new Bucket with the url as the bucket name (i.e test.potato.com).</li><li>From the dropdown Menu in the third step select “Grant Public Read Access”. If the options doesn’t exist, after creating the bucket go to the “Permissions Tab” -&gt; “Access Control List” then Under “Public Access” Click on Everyone and check “List Objects”.</li><li>Go to the newly created Bucket “Properties” tab and Enable “static website hosting” by choosing “Use this bucket to host a website”.</li><li>set “index.html” as both the Error &amp; Index pages since the Frontend router will handle server 404 errors.</li><li>Go to “Bucket Policy” under “Permissions” and attach S3:GetObject permissions to the s3 bucket. Replace &lt;YOUR_BUCKET_NAME&gt; with your newly created bucket’s name.</li></ol><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;AddPerm&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;YOUR_BUCKET_NAME&gt;/*&quot;<br>        }<br>    ]<br>}</pre><p>6. Enable CORS.. In the “CORS Configuration” tab, add the following</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;CORSConfiguration xmlns=&quot;http://s3.amazonaws.com/doc/2006-03-01/&quot;&gt;<br>&lt;CORSRule&gt;<br>    &lt;AllowedOrigin&gt;*&lt;/AllowedOrigin&gt;<br>    &lt;AllowedMethod&gt;GET&lt;/AllowedMethod&gt;<br>    &lt;MaxAgeSeconds&gt;3000&lt;/MaxAgeSeconds&gt;<br>    &lt;AllowedHeader&gt;Authorization&lt;/AllowedHeader&gt;<br>&lt;/CORSRule&gt;<br>&lt;/CORSConfiguration&gt;</pre><p>7. (Optional) Add a deploy script for your package.json so that you can deploy by simply running yarn deploy from your project. This requires having the aws-cli installed, you can install it from <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">here</a> if you don’t have it and set it up by running aws configure</p><pre>// package.json<br>&quot;scripts&quot;: {<br>  &quot;deploy:live&quot;: &quot;npm run build &amp;&amp; aws s3 sync dist/    s3://&lt;YOUR_S3_BUCKET_NAME&gt; --delete &amp;&amp; npm run-script invalidate-cache:live&quot;,</pre><pre>  &quot;invalidate-cache:live&quot;: &quot;aws configure set preview.cloudfront true &amp;&amp; aws cloudfront create-invalidation --distribution-id &lt;CLOUDFRONT_DISTRIBUTION_ID&gt; --paths &#39;/*&#39;&quot;}</pre><p>Basically what this script does is it will run you build script, then copy your dist/ folder’s content generated by the build step to the S3 Bucket and delete files that exist remotely but not in the local folder thanks to the --delete flag. After that you might need to invalidate the cache for your CloudFront distribution which is what the second script does. We’ll be going through the CloudFront setup in the next step where you’ll be able to get the distribution id.</p><p>Your website should now be available under the link provided if you go to “Static website hosting”.</p><h4>Setup CloudFront</h4><blockquote>Amazon CloudFront is a fast content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency, high transfer speeds, all within a developer-friendly environment. CloudFront is integrated with AWS — both physical locations that are directly connected to the AWS global infrastructure, as well as other AWS services. CloudFront works seamlessly with services including AWS Shield for DDoS mitigation, Amazon S3, Elastic Load Balancing or Amazon EC2 as origins for your applications, and Lambda@Edge to run custom code closer to customers’ users and to customize the user experience.</blockquote><p>To Setup a CloudFront distribution go to “CloudFront” from the AWS console and follow these steps:</p><ol><li>Click “Create distribution” and choose “Web distrubution”.</li><li>Set the origin domain name to be the newly created s3 bucket.</li><li>Choose “Redirect HTTP to HTTPS”, to enable https.</li><li>To enable gzip compression for faster load times check “Compress Objects Automatically”.</li><li>Set the default root object to index.html so it redirects / to /index.html</li><li>Under “Alternative Domain names (cnames)” enter the URLs where you want your website to be accessible from. (in this case the s3 bucket name or subdomains that your ssl certificate supports, i.e: test.potato.com)</li><li>(Optional) Choose a custom SSL Certificate if you have one or you can request one from AWS Certificate Manager (ACM).</li><li>Click Create Distribution and wait until the distribution is created.</li></ol><p>Your website should be now accessible via the CloudFront distribution’s URL. Next we’ll be looking on how to make it available via a Custom Domain name as we provided in the cnames in the previous step.</p><h4>Configure Route53</h4><blockquote>Amazon Route 53 is a highly available and scalable cloud <a href="https://aws.amazon.com/route53/what-is-dns/">Domain Name System (DNS)</a> web service. It is designed to give developers and businesses an extremely reliable and cost effective way to route end users to Internet applications by translating names like <a href="http://www.example.com/">www.example.com</a> into the numeric IP addresses like 192.0.2.1 that computers use to connect to each other. Amazon Route 53 is fully compliant with IPv6 as well.</blockquote><p>Now we need to make changes to our DNS configuration to add an alias domain name that points to our newly created CloudFront distribution. This assumes you already have a HostedZone created and have purchased a domain through AWS.</p><ol><li>From the AWS console go to Route 53.</li><li>Click on your hosted zone.</li><li>Create a new Record Set with a name that matches the name you provided in your CloudFront distribution’s cname/alternative domain names.</li><li>Click “Alias” and under “Alias Target” choose your newly deployed CloudFront distribution from the autocomplete dropdown list then click create.</li><li>(Optional) Repeat these steps with a record set of type “AAAA (IPv6)” instead of “A IPv4” to support IPv6.</li></ol><p>That’s it, you now have a fully deployed functional website that you can access via a custom domain. Your website supports HTTPs and HTTP/2 via a custom SSL certificate and you can easily deploy your website by running yarn deploy from your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f77cd652c6" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/deploying-a-web-app-on-aws-using-s3-cloudfront-45f77cd652c6">How to deploy web apps to AWS using S3 &amp; CloudFront</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automate your releases, versioning & release notes like a boss]]></title>
            <link>https://itnext.io/automate-your-releases-versioning-and-release-notes-with-semantic-release-d5575b73d986?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5575b73d986</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 21:47:22 GMT</pubDate>
            <atom:updated>2021-07-07T15:13:17.492Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we’ll explore how to automate releases, changelog, release notes generation and semantic versioning via <a href="https://github.com/semantic-release/semantic-release">semantic-release</a></p><p>What if I told you that with one command, you can:</p><ol><li>bump your package.json version to the right semver version</li><li>create a github release</li><li>create a git tag</li><li>generate a changelog that includes the release notes</li><li>push the changes to your git repository</li><li>publish your package to npm</li></ol><h4>Motivation</h4><p>Whether you have an open source project or work in a private company on a project that other people use in their projects, you probably need to communicate the changes you make to your project, so that others can understand what changed and know if there’re any breaking changes. Some reasons you might want to automate your releases are to:</p><ol><li>Follow semantic versioning in order to reflect project changes to consumers and differentiate between features releases, bug fixes and breaking changes.</li><li>Generate release notes/changelog so that other developers using your library can understand what exactly are the changes included in every release and their implications.</li><li>Communicate changes to clients and/or project managers.</li><li>Make releases part of your continuous integration system.</li><li>The process of manually generating releases, bumping versions and creating release notes can be painful, error prone and emotional.</li><li>Automatically create a git tag and publish the new version of your library on npm.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*b_PIl6U0oY2qsulaMU6Vmg.jpeg" /></figure><p>What if every pull request or commit you made to your release branch would automatically generate you a changelog, figure out the required version bump if any, bump the version for you as well as release your library automatically?</p><p>Meet <a href="https://github.com/semantic-release/semantic-release">semantic-release</a>. Before we set things up there are two requirements for using semantic-release: “Semantic Versioning” and “Conventional Commits”.</p><h4>Semantic Versioning</h4><p>Semantic versioning provides a way to have meaningful version numbers that represent that development of your project.</p><blockquote>Given a version number MAJOR.MINOR.PATCH, increment the:</blockquote><blockquote>MAJOR version when you make incompatible API changes,</blockquote><blockquote>MINOR version when you add functionality in a backwards-compatible manner, and</blockquote><blockquote>PATCH version when you make backwards-compatible bug fixes.</blockquote><blockquote>Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.</blockquote><h4>Conventional Commits</h4><blockquote>Conventional commits are a specification for adding human and machine readable meaning to commit messages</blockquote><p>If you’re not familiar with conventional commits take a look at <a href="https://www.conventionalcommits.org/en/v1.0.0-beta.2/">conventional commits</a> or <a href="https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#commits">Angular commit style</a>. Basically your commit messages should start with one of the following.</p><ul><li><em>feat: A new feature</em></li><li><em>fix: A bug fix</em></li><li><em>docs: Documentation only changes</em></li><li><em>style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)</em></li><li><em>refactor: A code change that neither fixes a bug nor adds a feature</em></li><li><em>perf: A code change that improves performance</em></li><li><em>test: Adding missing or correcting existing tests</em></li><li><em>chore: Changes to the build process or auxiliary tools and libraries such as documentation generation</em></li></ul><h3>Semantic-Release Configuration</h3><p>Now to the actual setup:</p><p>1. First you need to install semantic-release and the plugins you intend to use based on your configuration, you can see a list of all the available plugins <a href="https://github.com/semantic-release/semantic-release/blob/caribou/docs/usage/plugins.md">here</a>.</p><pre>npm i -D semantic-release @semantic-release/{git,commit-analyzer,release-notes-generator,npm,changelog} </pre><p>2. Next, follow the documentation <a href="https://github.com/semantic-release/semantic-release/blob/caribou/docs/usage/configuration.md#configuration">here </a>to configure semantic release based on your own needs. My personal configuration looks as follows:</p><pre>// package.json<br>&quot;release&quot;: {<br>     &quot;plugins&quot;: [<br>      &quot;@semantic-release/commit-analyzer&quot;,<br>      &quot;@semantic-release/release-notes-generator&quot;,<br>// if you dont want to publish on npm registry, you can set npmPublish to false </pre><pre>      [&quot;@semantic-release/npm&quot;,{&quot;npmPublish&quot;:false}],<br>      &quot;@semantic-release/changelog&quot;,<br>      &quot;@semantic-release/git&quot;<br>    ],<br>    &quot;branch&quot;: &quot;master&quot;<br>  }</pre><p>3. You should now be able to automatically create a release by running npx semantic-release from your Continuous Integration system or even manually with the --no-ci flag.</p><h3>Continuous Integration Setup</h3><h4>Manual releases With Github</h4><p>All you need is to set a GH_TOKEN environment variable and you’re good to go.</p><h4>With Bitbucket Pipelines</h4><p>You can use one of the following <a href="https://github.com/semantic-release/semantic-release/blob/master/docs/recipes/README.md">CI recipes</a>, in my case I’m using a private bitbucket repository and pipelines as a CI along with a private npm registry where I want to publish my library to, so we need to do some extra work.</p><ol><li>You can follow the steps provided <a href="https://npme.npmjs.com/docs/tutorials/pipelines.html">here</a> by npm to configure pipelines with your private registry and npm token.</li><li>First we need to give access to our CI to publish our library on npm and set the npm registry we’re using in case we’re publishing to a private registry. We can do this by setting the NPM_REGISTRY_URL &amp; NPM_TOKEN environment variables in the repository’s pipelines’ settings.</li><li>Add an SSH Key to your pipelines settings from the repository’s pipelines’ settings on bitbucket so that it can access the private repository and can push release tags.</li><li>Create a bitbucket-pipelines.ymlin the root directory of the repository that will configure the build pipelines and trigger semantic-release via npx.</li></ol><pre># This is a sample build configuration for JavaScript.<br># Check our guides at https://confluence.atlassian.com/x/14UWN for more examples.<br># Only use spaces to indent your .yml configuration.<br># -----<br># You can specify a custom docker image from Docker Hub as your build environment.<br>image: node:latest</pre><pre>pipelines:<br>  default:<br>    - step:<br>        caches:<br>          - node<br>        script: # Modify the commands below to build your repository.<br>          # Generates a .npmrc file configured for installing private modules:<br>          #<br>          # NPM_REGISTRY_URL: the full URL of your private registry<br>          #                   defaults to registry.npmjs.org.<br>          # NPM_TOKEN: secret token for installing private modules. This<br>          #            this token can be found in your .npmrc, after logging in.<br>          - printf &quot;//`node -p \&quot;require(&#39;url&#39;).parse(process.env.NPM_REGISTRY_URL || &#39;https://registry.npmjs.org&#39;).host\&quot;`/:_authToken=${NPM_TOKEN}\nregistry=${NPM_REGISTRY_URL:-https://registry.npmjs.org}\n&quot; &gt;&gt; ~/.npmrc<br>          - npm install<br>          - npm test<br>          - npx semantic-release</pre><p>If you set everything up correctly, now every commit that will land in the master branch will trigger a release and execute the configured plugins. When merging feature pull requests you can use the Squash merge strategy which will squash an entire pull request of multiple commits into a single commit where you can even change the commit message to a conventional commit style one.</p><p>Make a conventional commit style commit message, merge it to the master branch and watch the magic happen.</p><p>A new pipeline was triggered and marked as green, semantic-release pushed a new commit generating the CHANGELOG.md file based on the previous commits and a new git tag was created with the semantically correct version and the package was published to my private npm registry. Pretty awesome, isn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVABA0PRhm0SBoCvl_iKpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pxh5zuzSCSyfArEZI5l6ew.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5575b73d986" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/automate-your-releases-versioning-and-release-notes-with-semantic-release-d5575b73d986">How to automate your releases, versioning &amp; release notes like a boss</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Improve your Angular application’s performance]]></title>
            <link>https://itnext.io/improve-your-angular-apps-performance-66032f63dc09?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/66032f63dc09</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 03:52:07 GMT</pubDate>
            <atom:updated>2020-10-10T19:18:27.552Z</atom:updated>
            <content:encoded><![CDATA[<p>Make the most out of Angular’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WZqDu2qAZGLMqBg1h5sIg.png" /></figure><h3>Reduce your bundle size</h3><p>If you don’t need to support old browsers, drop ES5 support. ES6 is already supported in all modern browsers.</p><ol><li>Go to your tsconfig.json and change the “target” from es5 to es6</li><li>When building your app use --es5-browser-support=false with ng build to exclude es5 browser polyfills from your bundle or permanently set it to false from angular.json.</li><li>Remove unused dependencies from your app.</li><li>Make your Angular services tree-shakeable. Don’t import and add them to the providers array in your ngModule. instead use the providedIn attribute when decorating your service with @Injectable() to let it be included in the bundle only if its injected or used in any other components/services as follows</li></ol><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class MyService {}</pre><p>5. Use Differential loading. if you’re using Angular version 8+ you should be able to use differential loading to avoid serving unneeded polyfills to modern browsers. simply add a browserslist file with the following content to your project and comment out all imports from src/pollyfills.ts except for zone.js, and make sure you have &quot;target&quot;: “es2015&quot;in your tsconfig.json.</p><pre>&gt; 0.5%<br>last 2 versions<br>Firefox ESR<br>Chrome 41 # Support for Googlebot<br>not dead<br>not IE 9-11 # For IE 9-11 support, remove &#39;not&#39;.</pre><p>6. Enable IVY <a href="https://next.angular.io/guide/ivy">https://next.angular.io/guide/ivy</a></p><h3>Lazy loading &amp; Code-splitting</h3><p>With Angular its super easy to lazy-load modules based on routes</p><p>instead of</p><pre>// app-routing.module.ts<br>const routes: Routes = [{</pre><pre>  path: home&#39;,</pre><pre>  component: HomeComponent</pre><pre>  }, {</pre><pre>  path: &#39;about&#39;,</pre><pre>  component: AboutComponent<br> }, {</pre><pre>  path: &#39;&#39;,</pre><pre>  redirectTo: &#39;home&#39;,</pre><pre>  pathMatch: &#39;full&#39;<br>}]</pre><p>use</p><pre>// app-routing.module.ts<br>const routes: Routes = [{</pre><pre>  path: home&#39;,</pre><pre>  component: HomeComponent</pre><pre>}, {</pre><pre>  path: &#39;about&#39;,</pre><pre>  loadChildren: &#39;./about/about.module#AboutModule&#39;<br>}, {</pre><pre>  path: &#39;&#39;,</pre><pre>  redirectTo: &#39;home&#39;,</pre><pre>  pathMatch: &#39;full&#39;<br>}]</pre><p>Notice we’re not lazyloading the home component since its the default route, that is required for the initial load. Lazy-loading it will cause Angular to trigger another http request which will actually harm our app’s performance.</p><h3><strong>Use Service Workers to Cache assets</strong></h3><p>Service workers are an awesome technology that allows you to develop Progressive Web Apps (PWA), even if you don’t want to build a PWA you can use them to cache assets and HTTP requests for an almost instant load time. Angular makes this super easy to opt-in with the angular-cli.</p><p>All you have to do is</p><pre>ng add @angular/pwa</pre><p>Note: Service Workers can only be installed if your website supports HTTPS which you should be doing anyway.</p><h3>Avoid Memory Leaks</h3><p>Unsubscribe from your event listeners, observables and setIntervals in ngOnDestroy, otherwise they will stay in memory and will keep running even if your component is destroyed.</p><h3>Debounce &amp; Throttle your event listeners</h3><p>If you have an event that gets fired frequently like an input change event or a scroll event, its better to debounce or throttle the event listener depending on the use-case to avoid running logic many times per frame affecting the FPS and performance of your app.</p><h3>Memoize &amp; Cache expensive functions</h3><p>This is not really Angular specific, but if you have expensive functions that get called multiple times. you can always cache the result and return the result from the cache instead of computing the result again.</p><h3>Minimize DOM Elements</h3><p>instead of creating wrapper divs that you don’t need, or avoiding the problem of not being able to apply two directives on the same div like *ngIf and *ngFor you can use &lt;ng-container&gt; which doesn’t add an extra DOM element to your tree.</p><h3>Optimise change detection</h3><p>These changes require a more in-depth understanding of Angular and how change detection works.</p><ol><li>Use <em>OnPush</em> changeDetection. setting changeDetection:ChangeDetectionStrategy.OnPush in your component essentially tells Angular to avoid deep checking input array/object and only run change detection for that component sub-tree if the inputs are not equal by reference. Which can save you both the time the framework takes for deep equality checks as well as the change detection time for that component and all other children of that component that would be marked as dirty as a result.</li><li>Use <em>trackBy</em>. If you’re rendering an array of items with *ngFor that may change over time, you can tell Angular to bind each DOM element with a value from an item in that array like an item’s id. The next time the array changes, Angular will only render/update the changed items instead of re-rendering the entire array of DOM elements.</li><li>Use <em>ngZone.runOutsideAngular. </em>If you use asynchronous APIs like setTimeout, setInterval and Promise in your component that does not change your component’s state in their callback and does not need to trigger change detection you can tell Angular not to trigger change detection when their callback is Executed.</li></ol><pre>ngZone.runOutsideAngular(() =&gt; {<br>  setTimeout(() =&gt; {<br>    doSomethingThatDoesntUpdateState()</pre><pre>  }, 5000)</pre><pre>})</pre><p>Or completely disable ngZone from your application and manually trigger change detection for asynchronous javascript APIs with applicationRef.tick() for a more advanced usecase</p><pre>platformBrowserDynamic().bootstrapModule(AppModule, {<br>      ngZone: &#39;noop&#39;;<br>})</pre><h3>Conclusion</h3><p>There are other things you can do to optimise your application’s performance, most of them already are enabled by default now like Pure Pipes, enableProdMode, AOT &amp; build-optimizer with ng build --prod .</p><p>This article was inspired by <a href="https://github.com/mgechev/angular-performance-checklist">angular-performance-checklist</a> written by <a href="https://medium.com/u/a7db01a91fcb">Minko Gechev</a>, If you’re interested about other performance optimisations you can do and more detailed explanations, you should check it out.</p><p>If you like my content and would like to support me, you can <a href="https://www.buymeacoffee.com/khaledosman">buy me a beer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66032f63dc09" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/improve-your-angular-apps-performance-66032f63dc09">How to Improve your Angular application’s performance</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJs graceful start & shutdown in a load balancer]]></title>
            <link>https://itnext.io/nodejs-graceful-start-shutdown-3ed16418ede3?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed16418ede3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 14:27:00 GMT</pubDate>
            <atom:updated>2021-07-07T15:12:47.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoCrQxSWimdw6-uIa-sqNw.jpeg" /></figure><p>To avoid problems when deploying, closing, starting and restarting your app, its important to make sure that the existing requests complete and prevent anymore requests from hitting your server before the server shuts down. This is called graceful shutdown.</p><p>Its also important to make sure that the server is able to make requests to the database before receiving client requests to be able to fulfill them, otherwise errors and race conditions might happen, this is what we call graceful start.</p><h4>Graceful start</h4><p>In a graceful start your app must successfully establish the connection with the database before accepting requests.</p><ol><li>App starts <em>(npm start)</em></li><li>App opens DB connections</li><li>App listens on port</li><li>App tells the load balancer that it’s ready for requests</li></ol><p>Lets see how we can achieve this in code.</p><pre>const server = http.createServer(app)<br>mongoose.connect(process.env.MONGO_URL)<br>  .then(db =&gt; {<br>    console.log(&#39;connected to mongo successfully&#39;)<br>    server.listen(port, err =&gt; {<br>      if (err) {<br>        console.log(&#39;something bad happened&#39;, err)<br>      } else {<br>        process.send = process.send || function () { }<br>        process.send(&#39;ready&#39;)<br>        console.log(`server is listening on ${port}`)<br>      }<br>    })<br>  })<br>  .catch(err =&gt; console.log(&#39;Mongo connection error&#39;, err))</pre><h4>Graceful shutdown</h4><p>In a graceful shutdown, your app must go through 5 steps:</p><ol><li>Receives a notification to stop</li><li>Asks the load balancer to stop receiving requests</li><li>Finishes all ongoing requests</li><li>Releases all resources (databases, queues…)</li><li>Exits</li></ol><p>lets see what this looks like in code</p><pre>// If the Node process ends, close the Mongoose connection<br>const sigs = [&#39;SIGINT&#39;, &#39;SIGTERM&#39;, &#39;SIGQUIT&#39;]<br>sigs.forEach(sig =&gt; {<br>  process.on(sig, () =&gt; {<br>    // Stops the server from accepting new connections and finishes existing connections.<br>    server.close(function (err) {<br>      if (err) {<br>        console.error(err)<br>        process.exit(1)<br>      }<br>      // close your database connection and exit with success <br>      // for example with mongoose<br>      mongoose.connection.close(function () {<br>        console.log(&#39;Mongoose connection disconnected&#39;)<br>        process.exit(0)<br>      })<br>    })<br>  })<br>})</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed16418ede3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/nodejs-graceful-start-shutdown-3ed16418ede3">NodeJs graceful start &amp; shutdown in a load balancer</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular for React Developers: Differences and Component API comparison]]></title>
            <link>https://itnext.io/angular-for-react-developers-63239f278158?source=rss-5c34e1116828------2</link>
            <guid isPermaLink="false">https://medium.com/p/63239f278158</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Khaled Osman]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 13:00:40 GMT</pubDate>
            <atom:updated>2020-10-10T19:18:58.327Z</atom:updated>
            <content:encoded><![CDATA[<p>This is not yet another Angular vs React article. I wrote this article for React developers curious about Angular and vice versa. I’m going to be exploring mostly the Component API in both frameworks, how they compare to each others and how they solve the same problems.</p><h4>Components:</h4><p>Let’s compare the component API in both frameworks. A very simple class component in React looks like this</p><pre>import React, { Component } from &#39;react&#39;<br>import &#39;./App.css&#39;</pre><pre>export class App extends Component {</pre><pre>  render () {</pre><pre>    return &lt;div&gt; Hello world &lt;/div&gt;</pre><pre>  }</pre><pre>}</pre><p>This would be the equivalent implementation in Angular</p><pre>import { Component } from &#39;@angular/core&#39;</pre><pre>@Component({</pre><pre>  selector: &#39;app-component&#39;,</pre><pre>  template: `&lt;div&gt; Hello world &lt;/div&gt;`,</pre><pre>  styleUrls: [&#39;./app.component.css&#39;]</pre><pre>})</pre><pre>export class AppComponent {}</pre><h4>Passing input to components &amp; handling events:</h4><p>In React you can pass input bindings to the component via props and you pass callback functions down to the child component the same way to handle events that happen in the child component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhlEsKTP_bqJ3z07wqhvdA.png" /></figure><p>In Angular you rely on the @Input() decorator to pass attribute bindings to child components, and the @Output() decorator to emit custom events to the parent component to handle. Lets see how this looks like in Angular</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM3-MdPxJiGWLfbs9yEZXg.png" /></figure><p>The child component has an EventEmitter that emits the event up to the parent component when the button is clicked. The parent component listens to the DOM/output event via (buttonClicked) and handles the implementation.</p><p>Another thing you may have noticed is that there’re no props or state, everything is attached to this instead, usually public variables are used in the template so this is the closest you can get to state in Angular. You may have also noticed the weird syntax with the square brackets and the parenthesis in the template. Which brings us to the templating difference in both frameworks.</p><h4>Templating:</h4><p>React relies on JSX for templating which is basically just Syntactic sugar that transpiles to JavaScript asReact.createElement() which is a wrapper around document.createElement().</p><p>Angular has its own Domain Specific Language (DSL) which allows us to write Angular specific html-like syntax on top of normal html. It also has its own compiler that compiles this syntax to html that the browser can understand. There’re mainly 3 main syntax you see in Angular’s DSL language. *,() and [].</p><p>() is used for Output and DOM events</p><p>[] is used for Input and specific DOM element attributes</p><p>*means it’s a Structural Directive. Something that will affect/change the DOM structure. like *ngForor *ngIf.</p><h4>LifeCycle Hooks</h4><p>Both frameworks have lifecycle hooks that represent the component’s rendering/update state. Below you can find each React lifecycle hook and its equivalent in Angular.</p><p>componentWillMount (deprecated) → ngOnInit</p><p>componentDidMount → ngAfterViewInit</p><p>componentWillUnmount → ngOnDestroy</p><p>componentWillReceiveProps (deprecated), getDerivedStateFromProps, componentWillUpdate, componentDidUpdate can all be replaced by ngOnChanges in Angular.</p><p>Unlike componentWillReceiveProps, ngOnChanges actually fires only when the component’s props/input bindings change, it has a changes object in the parameter which tells you exactly which specific props changed along with their current/previous values. So you don’t have to worry about it being triggered before every render unlikecomponentWillReceiveProps.</p><h4>Change Detection</h4><p>React relies on unidirectional data-flow and it uses something called virtual DOM to handle change detection, Virtual DOM is basically a JavaScript object representation of the DOM. It diffs and applies changes only to the parts that differ from the actual DOM after reconstructing the virtual dom.</p><p>Angular has its own Change Detection strategy built in that runs whenever Angular thinks some code might cause a change detection. i.e DOM events, asynchronous calls like setTimeout/setInterval/Promises and changes to Input variables. This allows both unidirectional data-flow as well as two-way data binding as preferred by the developer.</p><p>Angular achieves this via implementing their own wrapper around a library called zone.js which allows them to monkey patch async JavaScript APIs like setTimeout to run angular change detection after execution, so every time you run a setTimeout you execute angular’s changeDetection, if you have some async call that shouldn’t trigger change detection, you can opt out by using ngZone.runOutsideAngular(fn).</p><h4>Performance Optimisations</h4><p>Both Angular and React have a similar way to optimise their change detection. In React you can use PureComponent React.memo or shouldComponentUpdate which essentially tells react to skip rendering unless one of the props of the component changes (ref changes only). Allowing it to compare objects/arrays by reference instead of deeply checking them.</p><p>The equivalent of this in Angular is ChangeDetectionStrategy.OnPush Angular also has the possibility to completely detach the ChangeDetector and manually triggering changes. OnPush change detection can be set via the @Component decorator as follows:</p><pre>import { Component, ChangeDetectionStrategy } from &#39;@angular/core&#39;;</pre><pre>@Component({</pre><pre>  selector: &#39;app-root&#39;,</pre><pre>  templateUrl: &#39;./app.component.html&#39;,</pre><pre>  styleUrls: [&#39;./app.component.css&#39;],</pre><pre>  changeDetection: ChangeDetectionStrategy.OnPush</pre><pre>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;angular-performance-demo&#39;;</pre><pre>}</pre><p>Another common optimisation is when rendering lists is to use keys in React to tell the framework to render only new/deleted items in the array instead of replacing all DOM elements when an array changes. the equivalent of this in Angular is trackBy.</p><h4>Style Encapsulation</h4><p>A good reusable component is something you can plug somewhere else in your app and use without having to worry about side-effects or custom configuration.</p><p>In React if you want to make sure your css doesn’t bleed to other components you have to use solutions like css modules or css in javascript.</p><p>Angular has an option in its Component API to allow css to be encapsulated per Component or not encapsulated at all. The values for this attribute can be either via the browser’s ShadowDOM API or an Emulated mode where angular generates random ids and attaches them to the classes for each DOM element.</p><p>Style Encapsulation is enabled by default in Angular, to change the Encapsulation strategy you use the encapsulation property in the @Component decorator as follows:</p><pre>import { Component, ViewEncapsulation } from &#39;@angular/core&#39;;</pre><pre>@Component({</pre><pre>  selector: &#39;app-root&#39;,</pre><pre>  templateUrl: &#39;./app.component.html&#39;,</pre><pre>  styleUrls: [&#39;./app.component.css&#39;],</pre><pre>  encapsulation: ViewEncapsulation.ShadowDom</pre><pre>})</pre><pre>export class AppComponent {</pre><pre>  title = &#39;my-app&#39;;</pre><pre>}</pre><h4>Fragments</h4><p>Sometimes you need to have a wrapper element around your DOM elements, but you don’t want to introduce another DOM element to your tree, its a good common practice to minimise DOM elements in your app for performance and readability reasons. In React you can do this by wrapping your elements with &lt;React.Fragment&gt;.</p><p>Angular has a similar component, you can achieve that with &lt;ng-container&gt;.</p><h4>Props.Children, slots &amp; Transclusion</h4><p>To reuse some logic from your React component. React has offered multiple ways to do this, from <em>mixins, Higher Order Components, renderProps, props.children</em>. These are all different ways to solve the same problem that is rendering different content with the same functionality. Its usually advised to use <em>renderProps</em> over <em>HOCs</em> which is already very similar to props.children.</p><p>In Angular you can put your javaScript logic into services and rely on Transclusion/slots which is the equivalent to props.children in React. The following example will render content passed from the parent component’s template to the child one’s, you can also have multiple ng-contents that render in specific parts of your template:</p><pre>//child.component.html</pre><pre>&lt;div&gt;Children render here:<br>  &lt;ng-content&gt;&lt;/ng-content&gt;<br>&lt;/div&gt;</pre><pre>//parent.component.html<br>&lt;app-child-component&gt;I render in child component&lt;/app-child-component&gt;</pre><p>This is the equivalent in React</p><pre>//child.component.js<br>export function Child(props) {</pre><pre>  return (<br>    &lt;div&gt; Children render here:<br>    {this.props.children}<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Web components Compatibility</h4><p>Angular’s implementation of Components are somewhat similar and is compatible with the native browser implementation of the Custom Elements v1 spec as they support ShadowDOM, slots, custom events, css variables as well as equivalent lifecycle hooks.</p><p>In fact, you can compile your Angular components into native web components that you can use with any other framework or with no framework at all, similar to what <a href="https://stenciljs.com/">stencilJS</a> does.</p><p>React however seems to be more focused on having a declarative easy to use API for implementing business logic and UI components. for more info regarding custom elements compatibility with React see <a href="https://reactjs.org/docs/web-components.html">https://reactjs.org/docs/web-components.html</a></p><h4>Conclusion</h4><p>We took a look at Components both in Angular &amp; React. Hopefully, this sparked your curiosity to learn and/or try the other framework. Both frameworks have their own solutions to the same problems, that’s why it&#39;s more important to learn and understand the actual problem and its solution rather than its framework specific syntax and solution.</p><p>If you like my content and would like to show support, you can <a href="https://www.buymeacoffee.com/khaledosman">buy me a beer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63239f278158" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/angular-for-react-developers-63239f278158">Angular for React Developers: Differences and Component API comparison</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>