<?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 Shariifahdah on Medium]]></title>
        <description><![CDATA[Stories by Shariifahdah on Medium]]></description>
        <link>https://medium.com/@shariifahdah43?source=rss-1a21c507dd19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*49-kZmQ0csfNQJx8</url>
            <title>Stories by Shariifahdah on Medium</title>
            <link>https://medium.com/@shariifahdah43?source=rss-1a21c507dd19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:16:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shariifahdah43/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[Exploring Total.js UI: Mastering Data Binding with <ui-bind> Commands]]></title>
            <link>https://medium.com/@shariifahdah43/exploring-total-js-ui-mastering-data-binding-with-ui-bind-commands-4cde27c18771?source=rss-1a21c507dd19------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cde27c18771</guid>
            <dc:creator><![CDATA[Shariifahdah]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 15:30:31 GMT</pubDate>
            <atom:updated>2024-09-02T15:30:31.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMtjnbmVAtW7UVAlBb7RTQ.jpeg" /></figure><h3>Introduction</h3><p>When developing dynamic web applications, having control over data binding is essential for creating responsive and interactive user interfaces. <a href="https://docs.totaljs.com/components/">Total.js UI</a> provides powerful tools for this, particularly through the &lt;ui-bind&gt; directive. This blog post explores various &lt;ui-bind&gt; commands, detailing how each works and how to use them effectively in your projects.</p><p>To help you navigate through the key features and applications of these commands, we’ll break down each one and provide practical examples. Here’s what we’ll cover:</p><h3>Table of Contents</h3><ol><li><strong>Prerequisites</strong></li><li><strong>Understanding </strong><strong>config=&quot;text&quot;</strong></li><li><strong>Utilizing </strong><strong>config=&quot;template&quot;</strong></li><li><strong>Leveraging </strong><strong>config=&quot;html&quot;</strong></li><li><strong>Applying </strong><strong>config=&quot;val .D:value&quot;</strong></li><li><strong>Executing Functions with </strong><strong>config=&quot;exec:myfunction&quot;</strong></li><li><strong>Incorporating Delays with </strong><strong>config=&quot;val .D:value;delay:2000&quot;</strong></li></ol><h3>1. Prerequisites</h3><p>Before diving into this tutorial on Total.js UI, ensure you have the following prerequisites in place to effectively follow along and complete the projects:</p><p>1 <strong>Basic Knowledge of HTML and JavaScript:</strong></p><ul><li><strong>HTML:</strong> You should be comfortable with HTML tags, attributes, and basic page structure.</li><li><strong>JavaScript:</strong> Familiarity with JavaScript fundamentals, including variables, functions, and event handling, is necessary.</li><li><strong>jQuery:</strong> Total.js UI integrates jQuery for DOM manipulation and event handling. Although the use of jQuery is minimal, having a basic understanding of it will be beneficial.</li></ul><p>2 <strong>Access to a Modern Web Browser:</strong></p><ul><li>Use a modern web browser such as Google Chrome, Mozilla Firefox, or Microsoft Edge.</li></ul><p>3 <strong>Code Editor:</strong></p><ul><li>A good code editor is essential for writing and editing your code. Recommended options include:</li><li><a href="https://code.visualstudio.com/"><strong>Visual Studio Code</strong></a></li><li><a href="https://www.sublimetext.com/"><strong>Sublime Text</strong></a></li><li><a href="https://atom.io/"><strong>Atom</strong></a></li></ul><p>4 <strong>Internet Connection:</strong></p><ul><li>An active internet connection is required to access the CDN links for Total.js UI and other external libraries used in the projects.</li></ul><p>5 <strong>Basic Understanding of Data Binding Concepts:</strong></p><ul><li>While this blog will explain the concepts in detail, having a foundational understanding of data binding will help you grasp the concepts more efficiently.</li></ul><p>By ensuring you meet these prerequisites, you’ll be well-prepared to follow this tutorial and effectively apply the various &lt;ui-bind&gt; commands in Total.js UI, enhancing your ability to create dynamic and interactive web applications.</p><h3>Understanding config=&quot;text&quot;</h3><p>The <strong>config=”text”</strong> command is used to define the text content of an HTML element based on the data linked via the specified <strong>path</strong> attribute. This command displays the data as plain text within the HTML element, escaping any HTML tags to prevent undesired HTML execution.</p><p><strong>Key Features:</strong></p><ul><li><strong>Text Display</strong>: Shows the data as plain text.</li><li><strong>Dynamic Updates</strong>: Automatically updates the text when the data changes.</li><li><strong>HTML Escaping</strong>: Prevents HTML tag interpretation.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;user.name&quot; config=&quot;text&quot;&gt;&lt;/ui-bind&gt;</pre><p>If user.name is &quot;Alice&quot;, the element displays Alice. Changes to user.name will update the text accordingly.</p><h3>Utilizing config=&quot;template&quot;</h3><p>The config=&quot;template&quot; command compiles the HTML content as a Tangular template, allowing dynamic content rendering using the value variable. It supports jQuery selectors for efficient DOM updates, especially in versions 17 and later of Total.js.</p><p><strong>Key Features:</strong></p><ul><li><strong>Tangular Compilation</strong>: Renders HTML dynamically using Tangular.</li><li><strong>Efficient Updates</strong>: Uses jQuery selectors to optimize DOM updates.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;user.profile&quot; config=&quot;template&quot;&gt;<br>    &lt;script type=&quot;text/html&quot;&gt;<br>        &lt;div&gt;{{ value.name }}&lt;/div&gt;<br>        &lt;div&gt;{{ value.age }}&lt;/div&gt;        <br>    &lt;/script&gt;<br>&lt;/ui-bind&gt;</pre><p>If user.profile contains { name: &quot;John&quot;, age: 30 }, you can use {{value.name}} and {{value.age}} in the template to render this data dynamically.</p><h3>Leveraging config=&quot;html&quot;</h3><p>The config=&quot;html&quot; command sets the HTML content of an element based on the data linked via the path attribute. Unlike config=&quot;text&quot;, this command renders HTML tags included in the data, allowing for more complex content presentation.</p><p><strong>Key Features:</strong></p><ul><li><strong>HTML Rendering</strong>: Interprets and displays HTML content directly.</li><li><strong>Dynamic Content</strong>: Updates the HTML content when the data changes.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;some.path&quot; config=&quot;html&quot;&gt;&lt;/ui-bind&gt;</pre><p>If some.path is &quot;&lt;strong&gt;Hello, World!&lt;/strong&gt;&quot;, the element displays &quot;Hello, World!&quot; in bold.</p><h3>Applying config=&quot;val .D:value&quot;</h3><p>The config=&quot;val .D:value&quot; command is used to bind the value of an HTML input element to a data path. The .D selector targets the element where the value should be applied.</p><p><strong>Key Features:</strong></p><ul><li><strong>Value Binding</strong>: Links data values to form elements.</li><li><strong>Dynamic Updates</strong>: Automatically updates the input value when the data changes.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;some.path&quot; config=&quot;val .D:value&quot;&gt;<br>    &lt;input class=&quot;D&quot; /&gt;<br>&lt;/ui-bind&gt;</pre><p>If some.path is &quot;Hello&quot;, the &lt;input&gt; element will display &quot;Hello&quot;.</p><h3>Executing Functions with config=&quot;exec:myfunction&quot;</h3><p>The config=&quot;exec:myfunction&quot; command executes a specified function whenever the data at the path changes. This allows you to add custom logic or perform actions in response to data updates.</p><p><strong>Key Features:</strong></p><ul><li><strong>Function Execution</strong>: Runs a custom function on data change.</li><li><strong>Custom Logic</strong>: Enables complex responses to data updates.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;some.path&quot; config=&quot;exec:myfunction&quot;&gt;&lt;/ui-bind&gt;<br>&lt;script&gt;<br>    function myfunction(value, path, element) {<br>        console.log(&#39;UPDATED VALUE:&#39;, value);<br>    }<br>&lt;/script&gt;</pre><p>Every time some.path changes, myfunction logs the new value to the console.</p><h3>Incorporating Delays with config=&quot;val .D:value;delay:2000&quot;</h3><p>The config=&quot;val .D:value;delay:2000&quot; command binds a value to an input field with a delay before applying the update. This delay helps manage frequent updates and improve performance.</p><p><strong>Key Features:</strong></p><ul><li><strong>Value Binding with Delay</strong>: Applies value updates with a specified delay.</li><li><strong>Performance Optimization</strong>: Reduces immediate update frequency.</li></ul><p><strong>Example:</strong></p><pre>&lt;ui-bind path=&quot;some.path&quot; config=&quot;val .D:value;delay:2000&quot;&gt;<br>    &lt;input class=&quot;D&quot; /&gt;<br>&lt;/ui-bind&gt;</pre><p>Updates to some.path will be applied to the &lt;input&gt; after a 2-second delay.</p><h3>Conclusion</h3><p>By understanding and effectively using these &lt;ui-bind&gt; commands, you can enhance the dynamism and responsiveness of your web applications with <a href="https://docs.totaljs.com/components/">Total.js UI</a>. Each command provides specific functionality to manage data binding in various scenarios, helping you create a seamless and interactive user experience. Leveraging these tools will enable you to build more engaging and efficient interfaces, demonstrating the power of Total.js UI in modern web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cde27c18771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a lastseen tracking application using Total.js]]></title>
            <link>https://medium.com/@shariifahdah43/creating-a-lastseen-tracking-application-using-total-js-70d5fea185c2?source=rss-1a21c507dd19------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d5fea185c2</guid>
            <dc:creator><![CDATA[Shariifahdah]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 14:51:04 GMT</pubDate>
            <atom:updated>2024-07-30T14:51:04.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56LAdarZzt2rNK5MCW8Cgg.jpeg" /></figure><h3>Introduction</h3><p>In this tutorial, we will build a <strong>Lastseen</strong> application using <a href="https://www.totaljs.com/">Total.js</a>. The goal is to provide a step-by-step guide on creating an <strong>API</strong> that tracks and retrieves the last seen timestamp for users.</p><p>The <strong>Lastseen</strong> application will include an <strong>API</strong> with endpoints to update and retrieve the last seen timestamp for a user. This is useful for tracking user activity or presence in various applications.</p><p>To achieve this, we will follow the steps outlined in the table of contents below.</p><p>1. Setting Up the Development Environment</p><p>2 .Configuring API Routes<br> <br>3 .Defining Data Schemas<br> <br>4 .Testing and Validation<br> <br>5 .Deployment with Docker</p><ul><li>Conclusion</li></ul><h3>1. Setting Up the Development Environment</h3><h3>Installing Total.js</h3><p>To begin, you need to install <strong>Total.js</strong>. This can be done via npm:</p><pre>npm install total4</pre><h3>Configuring the basic application</h3><p>Create a basic configuration for your <strong>Total.js</strong> application. Set up the entry point by creating an index.js file with the following content:</p><pre>var port = process.argv[2];<br>require(&#39;total4/debug&#39;)({ port: port || 4000 });</pre><p>This configuration ensures that the <strong>Total.js</strong> server listens on the specified port or defaults to 4000.</p><h3>2. Configuring the API Routes</h3><h3>Configuring routes in controllers/lastseen.js</h3><p>To set up the <strong>API</strong> routes, create a controllers/lastseen.js file and define the routes for updating and retrieving last seen timestamps:</p><pre>exports.install = function() {<br>    ROUTE(&#39;POST /api/update/{id}/    *Lastseen --&gt; update&#39;);<br>    ROUTE(&#39;GET /api/retrieve/{id}/   *Lastseen --&gt; retrieve&#39;);<br>};</pre><p>These routes define endpoints for:</p><ul><li><strong>POST /api/update/{id}/</strong>: Updates the last seen timestamp for the specified user id.</li><li><strong>GET /api/retrieve/{id}/</strong>: Retrieves the last seen timestamp for the specified user id.</li></ul><h3>3. Defining Data Schemas</h3><h3>Creating the schema for updates and retrieval in schemas/lastseen.js</h3><p>Create a schemas/lastseen.js file to define the data schema for updating and retrieving last seen information:</p><pre>NEWSCHEMA(&#39;Lastseen&#39;, function(schema) {<br><br>    schema.action(&#39;update&#39;, {<br>        name: &#39;update lastseen&#39;,<br>        params: &#39;*id:String&#39;,<br>        action: async function($) {<br>            const now = new Date();<br>            const item = await DATA.read(&#39;nosql/lastdb&#39;).where(&#39;userid&#39;, $.params.id).promise();<br>            if (!item)<br>                DATA.insert(&#39;nosql/lastdb&#39;, { userid: $.params.id, lastseen: now }).callback($.done());<br>            else<br>                DATA.update(&#39;nosql/lastdb&#39;, { lastseen: now }).where(&#39;userid&#39;, $.params.id).callback($.done());<br>        }<br>    });<br><br>    schema.action(&#39;retrieve&#39;, {<br>        name: &#39;retrieve lastseen&#39;,<br>        params: &#39;*id:String&#39;,<br>        action: function($) {<br>            DATA.read(&#39;nosql/lastdb&#39;).where(&#39;userid&#39;, $.params.id).error(404).callback($.callback);<br>        }<br>    });<br><br>});</pre><p>This schema defines:</p><ul><li><strong>update</strong>: Updates the last seen timestamp for a user specified by id.</li><li><strong>retrieve</strong>: Retrieves the last seen timestamp for a user specified by id.</li></ul><h3>Running the Application</h3><p>To run the Lastseen application locally, follow these steps:</p><ol><li>Ensure you have Total.js installed and configured as described in the previous sections.</li><li>Navigate to your application directory and execute the following command to start the server:</li></ol><pre>node index.js<br>#or node index(port)</pre><p>3. The application will be accessible on the specified port (default is 4000). You can verify its functionality by using tools like Postman to test the API endpoints.</p><h3>4. Testing and Validation</h3><h3>Testing endpoints for data updates and retrieval</h3><p>To test the API endpoints, use tools like Postman or cURL. Here are the expected responses for each endpoint:</p><p>1 <strong>Test the Update Endpoint</strong></p><ul><li><strong>URL</strong>: <a href="http://localhost:4000/api/update/%7Bid%7D/">http://localhost:4000/api/update/{id}/</a></li><li><strong>Method</strong>: POST</li><li><strong>Example cURL Command</strong>:</li></ul><pre>curl -X POST http://localhost:4000/api/update/12345/</pre><ul><li><strong>Expected Response</strong>:</li><li><strong>Success</strong>:</li></ul><pre>       {<br>         &quot;success&quot;: true<br>       }</pre><ul><li><strong>Failure</strong>: If the user ID is invalid or there is an issue with the database, you might receive:</li></ul><pre>      {<br>         &quot;success&quot;: false,<br>         &quot;code&quot;: 400,<br>         &quot;message&quot;: &quot;Error message&quot;<br>       }</pre><p>2 <strong>Test the Retrieve Endpoint</strong></p><ul><li><strong>URL</strong>: <a href="http://localhost:4000/api/retrieve/%7Bid%7D/">http://localhost:4000/api/retrieve/{id}/</a></li><li><strong>Method</strong>: GET</li><li><strong>Example cURL Command</strong>:</li></ul><pre>curl http://localhost:4000/api/retrieve/12345/</pre><ul><li><strong>Expected Response</strong>:</li><li><strong>Success</strong>:</li></ul><pre>     {<br>         &quot;success&quot;: true,<br>         &quot;data&quot;: {<br>           &quot;userid&quot;: &quot;12345&quot;,<br>           &quot;lastseen&quot;: &quot;2024-07-29T12:00:00.000Z&quot;  // Example timestamp<br>         }<br>       }</pre><ul><li><strong>Failure</strong>: If the user ID does not exist or there is an issue with the database, you might receive:</li></ul><pre>      {<br>         &quot;success&quot;: false,<br>         &quot;code&quot;: 404,<br>         &quot;message&quot;: &quot;User not found&quot;<br>       }</pre><p>These responses will help you verify that the API is functioning correctly for both updating and retrieving last seen timestamps.</p><h3>5. Deployment with Docker</h3><p>Deploying the <strong>Lastseen</strong> application using <strong>Docker</strong> simplifies the deployment process and ensures consistency across different environments. Follow these steps to containerize and deploy your application:</p><h3>Creating a Dockerfile</h3><ol><li><strong>Create a </strong><strong>Dockerfile</strong> in the root directory of your project:</li></ol><pre># Use an official Node.js runtime as a parent image<br>   FROM node:20-alpine<br><br>   # Set the working directory in the container<br>   WORKDIR /app<br>   <br>  # Copy the rest of the application code<br>   COPY . .<br>   <br>   # Install app dependencies<br>   RUN npm init -y &amp;&amp; npm install total4<br><br>   # Expose port 4000<br>   EXPOSE 4000<br><br>   # Define the command to run the application<br>   CMD [ &quot;node&quot;, &quot;index.js&quot; ]</pre><p>2 <strong>Build the Docker Image</strong></p><p>Run the following command in the terminal from your project’s root directory:</p><pre>docker build -t lastseen-app</pre><p>3 <strong>Run the Docker Container</strong></p><p>Use the following command to start a container from the image:</p><pre>docker run -d -p 4000:4000 lastseen-app</pre><p>This command runs the container in detached mode and maps port 4000 on your host to port 4000 on the container.</p><h3>Verifying the Deployment</h3><p>After starting the <strong>Docker</strong> container, you can verify the deployment by accessing the API endpoints:</p><ul><li><strong>Update Endpoint</strong>:</li></ul><pre>curl -X POST http://localhost:4000/api/update/12345/</pre><ul><li><strong>Retrieve Endpoint</strong>:</li></ul><pre>curl http://localhost:4000/api/retrieve/12345/</pre><p>Ensure that the responses are as expected to confirm that the application is running correctly inside the Docker container.</p><h3>Conclusion</h3><p>Building the Lastseen application with Total.js allows you to efficiently track and retrieve user timestamps. Containerizing this application with Docker simplifies the deployment process and ensures consistent performance across different environments. By following the steps outlined in this tutorial, you can not only deploy and manage your application effectively but also enhance its scalability and portability. Docker ensures that your Lastseen application runs reliably, regardless of the underlying infrastructure. For further reading and additional resources, refer to the links below.</p><ul><li><strong>Total.js Enterprise</strong>: <a href="https://www.totaljs.com/enterprise">Total.js Enterprise</a></li><li><strong>GitHub</strong>: <a href="https://github.com/totaljs">Total.js on GitHub</a></li><li><strong>Stack Overflow</strong>: <a href="https://stackoverflow.com/questions/tagged/total.js">Total.js questions on Stack Overflow</a></li><li><strong>Telegram</strong>: <a href="https://t.me/totaljs">Total.js Telegram group</a></li><li><strong>WhatsApp</strong>: <a href="https://chat.whatsapp.com/IgyfyySDuOlH3WF1Iqa33o">Total.js WhatsApp group</a></li><li><strong>Twitter</strong>: <a href="https://twitter.com/totalframework">Total.js on Twitter</a></li><li><strong>Facebook</strong>: <a href="https://www.facebook.com/totaljs.web.framework/">Total.js on Facebook</a></li><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/groups/8109884">Total.js LinkedIn group</a></li><li><strong>Reddit</strong>: <a href="https://www.reddit.com/r/totaljs/">Total.js subreddit</a></li><li><strong>Discord</strong>: <a href="https://discord.gg/Vwd6rAp4">Total.js Discord server</a></li><li><strong>Slack</strong>: <a href="https://totaljs.slack.com/">Total.js Slack channel</a></li><li>— **Slack**: [Total.js Slack channel](https://totaljs.slack.com/)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d5fea185c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create some debuglinks API with Total.js]]></title>
            <link>https://medium.com/@shariifahdah43/how-to-create-some-debuglinks-api-with-total-js-838110ec5121?source=rss-1a21c507dd19------2</link>
            <guid isPermaLink="false">https://medium.com/p/838110ec5121</guid>
            <dc:creator><![CDATA[Shariifahdah]]></dc:creator>
            <pubDate>Tue, 28 May 2024 14:49:24 GMT</pubDate>
            <atom:updated>2024-05-28T16:02:04.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z7f7SNk40_fEwiWu.jpg" /></figure><h3>Introduction</h3><p>In this tutorial, we will guide you through creating an API using Total.js, a powerful and flexible Node.js framework. We will cover setting up the environment, defining routes, creating data schemas, handling authentication, managing errors, and finally, testing the API endpoints. By the end of this guide, you will have a fully functional API.</p><h3>Table of Contents</h3><p>1.Introduction</p><ul><li>Presentation of the API to create with Total.js</li><li>Presentation of the files and their structure</li></ul><p>2.Setting up the development environment</p><ul><li>Installing Total.js</li><li>Configuring the base application</li></ul><p>3.Creating API routes</p><ul><li>Configuring routes in controllers/user.js</li><li>Configuring routes in controllers/api.js</li></ul><p>4.Defining data schemas</p><ul><li>Creating the user schema in schemas/users.js</li><li>Creating the links schema in schemas/links.js</li></ul><p>5.Handling authentication</p><ul><li>Defining the authentication function in definitions/auth.js</li><li>Creating user sessions in definitions/func.js</li></ul><p>6.Managing errors</p><p>7.Testing the endpoint</p><p>8.Conclusion</p><ul><li>Recap of the steps</li><li>Next steps and suggestions to improve the API</li></ul><h3>Setting up the development environment</h3><h3>Installing Total.js</h3><p>First, you need to install Total.js. You can do this using npm:</p><pre>npm install total4</pre><h3>Configuring the base application</h3><p>Create a new file named index.js and set up the basic configuration to run the Total.js application on port 8000:</p><pre>require(&#39;total4/debug&#39;)({ port: 8000 });</pre><h3>Creating API routes</h3><h3>Configuring routes in controllers/user.js</h3><p>Define routes for user operations such as profile, registration, login, and logout in controllers/user.js:</p><pre>exports.install = function() {<br>    ROUTE(&#39;GET   /api/user/profile/   *Users --&gt; profile&#39;);<br>    ROUTE(&#39;POST  /api/user/register/  *Users --&gt; register&#39;);<br>    ROUTE(&#39;POST  /api/user/login/     *Users --&gt; login&#39;);<br>    ROUTE(&#39;GET   /api/user/logout/    *Users --&gt; logout&#39;);<br>};</pre><h3>Configuring routes in controllers/api.js</h3><p>Define routes for link operations such as querying and inserting links in controllers/api.js:</p><pre>exports.install = function() {<br>    ROUTE(&#39;+GET   /api/links/   *Links --&gt; query&#39;);<br>    ROUTE(&#39;+POST  /api/links/   *Links --&gt; insert&#39;);<br>};</pre><h3>Defining data schemas</h3><h3>Creating the user schema in schemas/users.js</h3><p>Define the user schema to handle actions like profile, registration, login, and logout in schemas/users.js:</p><pre>NEWSCHEMA(&#39;Users&#39;, function(schema) {<br>    schema.action(&#39;profile&#39;, {<br>        name: &#39;Show user profile&#39;,<br>        action: function($) {<br>            $.callback($.user);<br>        }<br>    });<br><br>    schema.action(&#39;register&#39;, {<br>        name: &#39;User registration&#39;,<br>        input: &#39;*username:String, *password:String, *confirm:String&#39;,<br>        action: async function($, model) {<br>            if (model.password !== model.confirm) {<br>                $.invalid(&#39;@(Passwords do not match)&#39;);<br>                return;<br>            }<br>            model.id = UID();<br>            model.dtcreated = NOW;<br>            model.sa = false;<br>            FUNC.create_session(model, $, function(session) {<br>                model.password = model.password.sha256(CONF.passwordizer);<br>                DATA.insert(&#39;nosql/user&#39;, model).callback(function(err) {<br>                    if (err) {<br>                        $.invalid(err);<br>                    } else {<br>                        $.success(session);<br>                    }<br>                });<br>            });<br>        }<br>    });<br><br>    schema.action(&#39;login&#39;, {<br>        name: &#39;User login&#39;,<br>        input: &#39;*username:String, *password:String&#39;,<br>        action: async function($, model) {<br>            var user = await DATA.read(&#39;nosql/user&#39;, { username: model.username }).fields(&#39;id, password&#39;).promise();<br>            if (!user) {<br>                $.invalid(&#39;@(User not found)&#39;);<br>                return;<br>            }<br>            if (user.password !== model.password.sha256(CONF.passwordizer)) {<br>                $.invalid(&#39;@(Invalid password)&#39;);<br>                return;<br>            }<br>            FUNC.create_session(user, $, function(session) {<br>                $.success(session);<br>            });<br>        }<br>    });<br><br>    schema.action(&#39;logout&#39;, {<br>        name: &#39;User logout&#39;,<br>        action: async function($) {<br>            await DATA.remove(&#39;nosql/session&#39;).where(&#39;userid&#39;, $.user.id).promise();<br>            $.success();<br>        }<br>    });<br>});</pre><p>Define the links schema to handle actions like querying and inserting links in schemas/links.js:</p><pre>NEWSCHEMA(&#39;Links&#39;, function(schema) {<br>    schema.action(&#39;query&#39;, {<br>        name: &#39;List links&#39;,<br>        query: &#39;search:String&#39;,<br>        action: function($) {<br>            var builder = DATA.find(&#39;nosql/link&#39;);<br>            $.query.search &amp;&amp; builder.search(&#39;search&#39;, $.query.search);<br>            builder.where(&#39;userid&#39;, $.user.id).callback($.callback);<br>        }<br>    });<br><br>    schema.action(&#39;insert&#39;, {<br>        name: &#39;Insert new link&#39;,<br>        input: &#39;*name:String, link:String, category:String, hashtags:Array&#39;,<br>        action: function($, model) {<br>            model.userid = $.user.id;<br>            model.username = $.user.username;<br>            model.id = UID();<br>            model.dtcreated = NOW;<br>            model.search = (model.title + &#39; &#39; + model.link + &#39; &#39; + model.category + &#39; &#39; + model.hashtags).toSearch();<br>            DATA.insert(&#39;nosql/link&#39;, model).callback($.done(model.id));<br>        }<br>    });<br>});</pre><h3>Handling authentication</h3><h3>Defining the authentication function in definitions/auth.js</h3><p>Define the function for authenticating requests in definitions/auth.js:</p><pre>var sessions = {};  // Initialize an empty object to store sessions in cache<br><br>AUTH(async function($) {<br>    var token = $.headers[&#39;authorization&#39;];  // Retrieve the authorization token from the request headers<br>    if (!token) {  // If no token is present, mark the request as invalid and return<br>        $.invalid();<br>        return;<br>    }<br><br>    var data = DECRYPTREQ($.req, token, CONF.passwordizer);  // Decrypt the token using the encryption key from the configuration<br>    if (!data) {  // If decryption fails, mark the request as invalid and return<br>        $.invalid();<br>        return;<br>    }<br><br>    var session = sessions[data.id];  // Look for the session in the cache using the ID from the decrypted token<br><br>    if (session) {  // If the session is found in the cache<br>        if (session.expire &gt; NOW) {  // Check if the session has not expired<br>            $.success(session);  // If the session is valid, return the session successfully<br>        } else {<br>            $.invalid();  // If the session has expired, mark the request as invalid<br>        }<br>    } else {  // If the session is not found in the cache<br>        session = await DATA.read(&#39;nosql/session&#39;).id(data.id).promise();  // Look for the session in the database<br><br>        if (!session) {  // If the session is not found in the database, mark the request as invalid<br>            $.invalid();<br>            return;<br>        }<br><br>        var user = await DATA.read(&#39;nosql/user&#39;).fields(&#39;id, username, sa&#39;).id(session.userid).promise();  // Retrieve the user information associated with the session<br>        user.sessionid = session.id;  // Add the session ID to the user<br>        session.sa = user.sa;  // Add the admin rights to the session<br>        session.username = user.username;  // Add the username to the session<br>        sessions[data.id] = session;  // Store the session in the cache<br>        $.success(session);  // Mark the request as valid and return the session<br>    }<br>});<br><br>ON(&#39;service&#39;, function(counter) {<br>    if (counter % 60 === 0)  // Every 60 cycles, clear the session cache to free up memory<br>        sessions = {};<br><br>    DATA.find(&#39;nosql/session&#39;).callback(function(err, items) {  // Look for all sessions in the database<br>        items.wait(async function(item, next) {  // For each session<br>            if (item.expire &lt; NOW) {  // If the session has expired<br>                await DATA.remove(&#39;nosql/session&#39;).id(item.id).promise();  // Remove the expired session from the database<br>            }<br>            next();  // Move to the next item<br>        }, NOOP);<br>    });<br>});</pre><h3>Creating user sessions in definitions/func.js</h3><p>Define the function to create user sessions in definitions/func.js:</p><pre>FUNC.create_session = async function(user, $, callback) {<br>    var session = {};<br>    session.id = UID();<br>    session.userid = user.id;<br>    session.ip = $.ip;<br>    session.ua = $.ua;<br>    session.expire = NOW.add(&#39;30 days&#39;);<br>    await DATA.insert(&#39;nosql/session&#39;, session).promise();<br>    var token = ENCRYPTREQ($.req, { id: session.id }, CONF.passwordizer);<br><br>    callback &amp;&amp; callback(token);<br>}</pre><h3>Managing errors</h3><h3>Implementing error handling functions in controllers/defaults.js</h3><p>Define error handling functions in controllers/defaults.js:</p><pre>exports.install = function() {<br>    ROUTE(&#39;#401&#39;, function() {<br>        error(401, &#39;Unauthorized request&#39;, this);<br>    });<br>    ROUTE(&#39;#408&#39;, function() {<br>        error(408, &#39;Request timeout&#39;, this);<br>    });<br>    ROUTE(&#39;#404&#39;, function() {<br>        error(404, &#39;Resource not found&#39;, this);<br>    });<br>};<br><br>function error(code, message, $) {<br>    $.json({ success: false, code, message });<br>}</pre><h3>Testing the endpoint</h3><h3>User Endpoints</h3><p>1.<strong> Profile Endpoint</strong><br> —<strong> Method</strong>: GET<br> — <strong>URL</strong>: `/api/user/profile`<br> — <strong>Headers</strong> : <br> — `Authorization`: Bearer token (obtained after login)<br> — <strong>Description</strong>: Retrieves the profile of the authenticated user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre>  curl -X GET &quot;http://localhost:8000/api/user/profile&quot; -H &quot;Authorization: Bearer YOUR_TOKEN_HERE&quot;</pre><p><strong>Expected Response</strong>:</p><pre> {<br>        &quot;id&quot;: &quot;USER_ID&quot;,<br>        &quot;username&quot;: &quot;USER_NAME&quot;,<br>        &quot;sa&quot;: false,<br>        &quot;sessionid&quot;: &quot;SESSION_ID&quot;<br>    }</pre><p>2. <strong>Register Endpoint</strong><br> —<strong> Method</strong>: POST<br> —<strong> URL</strong>: `/api/user/register`<br> — <strong>Body </strong>:</p><pre> {<br>            &quot;username&quot;: &quot;newuser&quot;,<br>            &quot;<br><br>            password&quot;: &quot;password123&quot;,<br>            &quot;confirm&quot;: &quot;password123&quot;<br>        }</pre><p>- <strong>Description</strong>: Registers a new user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre>  curl -X POST &quot;http://localhost:8000/api/user/register&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;username&quot;: &quot;newuser&quot;, &quot;password&quot;: &quot;password123&quot;, &quot;confirm&quot;: &quot;password123&quot;}&#39;</pre><p><strong>Expected Response</strong>:</p><pre> {<br>        &quot;success&quot;: true,<br>        &quot;token&quot;: &quot;SESSION_TOKEN&quot;<br>    }</pre><p>3. <strong>Login Endpoint</strong><br> — <strong>Method</strong>: POST<br> — <strong>URL</strong>: `/api/user/login`<br> — <strong>Body</strong>:</p><pre> {<br>            &quot;username&quot;: &quot;newuser&quot;,<br>            &quot;password&quot;: &quot;password123&quot;<br>        }</pre><p>- <strong>Description</strong>: Logs in an existing user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre> curl -X POST &quot;http://localhost:8000/api/user/login&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;username&quot;: &quot;newuser&quot;, &quot;password&quot;: &quot;password123&quot;}&#39;</pre><p><strong>Expected Response</strong>:</p><pre>{<br>        &quot;success&quot;: true,<br>        &quot;token&quot;: &quot;SESSION_TOKEN&quot;<br>    }</pre><p><strong>Logout Endpoint</strong><br> — <strong>Method</strong>: GET<br> — <strong>URL</strong>: `/api/user/logout`<br> — <strong>Headers</strong>: <br> — `Authorization`: Bearer token (obtained after login)<br> — <strong>Description</strong>: Logs out the authenticated user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre> curl -X GET &quot;http://localhost:8000/api/user/logout&quot; -H &quot;Authorization: Bearer YOUR_TOKEN_HERE&quot;</pre><p><strong>Expected Response</strong>:</p><pre> {<br>        &quot;success&quot;: true<br>    }</pre><h4>Link Endpoints</h4><p>1.<strong>Query Links Endpoint</strong><br> —<strong>Method</strong>: GET<br> —<strong> URL</strong>: `/api/links`<br> — <strong>Headers</strong>: <br> — `Authorization`: Bearer token (obtained after login)<br> — <strong>Query Parameters</strong>:<br> — `search`: Optional string to search for specific links<br> —<strong>Description</strong>: Retrieves links associated with the authenticated user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre> curl -X GET &quot;http://localhost:8000/api/links?search=example&quot; -H &quot;Authorization: Bearer YOUR_TOKEN_HERE&quot;</pre><p><strong>Expected Response</strong>:</p><pre>[<br>        {<br>            &quot;id&quot;: &quot;LINK_ID&quot;,<br>            &quot;name&quot;: &quot;Example Link&quot;,<br>            &quot;link&quot;: &quot;http://example.com&quot;,<br>            &quot;category&quot;: &quot;example&quot;,<br>            &quot;hashtags&quot;: [&quot;example&quot;, &quot;test&quot;],<br>            &quot;userid&quot;: &quot;USER_ID&quot;,<br>            &quot;username&quot;: &quot;USER_NAME&quot;,<br>            &quot;dtcreated&quot;: &quot;DATE_CREATED&quot;,<br>            &quot;search&quot;: &quot;search string&quot;<br>        }<br>    ]</pre><p><strong>2.Insert Link Endpoint</strong><br> — <strong>Method</strong>: POST<br> —<strong>URL</strong>: `/api/links`<br> —<strong>Headers</strong>: <br> — `Authorization`: Bearer token (obtained after login)<br> —<strong>Body</strong>:</p><pre>  {<br>            &quot;name&quot;: &quot;Example Link&quot;,<br>            &quot;link&quot;: &quot;http://example.com&quot;,<br>            &quot;category&quot;: &quot;example&quot;,<br>            &quot;hashtags&quot;: [&quot;example&quot;, &quot;test&quot;]<br>        }</pre><p>- <strong>Description</strong>: Inserts a new link associated with the authenticated user.</p><p><strong>Example Request (using cURL)</strong>:</p><pre> curl -X POST &quot;http://localhost:8000/api/links&quot; -H &quot;Authorization: Bearer YOUR_TOKEN_HERE&quot; -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;: &quot;Example Link&quot;, &quot;link&quot;: &quot;http://example.com&quot;, &quot;category&quot;: &quot;example&quot;, &quot;hashtags&quot;: [&quot;example&quot;, &quot;test&quot;]}&#39;</pre><p><strong>Expected Response</strong>:</p><pre>{<br>        &quot;success&quot;: true,<br>        &quot;id&quot;: &quot;NEW_LINK_ID&quot;<br>    }</pre><h3>Conclusion</h3><h3>Recap of the Steps</h3><p>In this tutorial, we covered the following steps to create an API using Total.js:</p><ol><li>Setting up the development environment by installing Total.js and configuring the base application.</li><li>Creating API routes for user and link operations.</li><li>Defining data schemas for users and links.</li><li>Implementing authentication to secure the API.</li><li>Managing errors to provide meaningful responses.</li><li>Testing the API endpoints to ensure they function correctly.</li></ol><h3>Next Steps and Suggestions to Improve the API</h3><p>To further enhance the API, consider the following:</p><ul><li>Implementing more detailed validation for inputs.</li><li>Adding additional endpoints to support update and delete operations for users and links.</li><li>Integrating with a frontend application or mobile app.</li><li>Adding logging and monitoring to keep track of API usage and errors.</li><li>Implementing rate limiting to prevent abuse of the API.</li></ul><p>By following these steps and continuously improving the API, you can create a robust and scalable application using Total.js.</p><p><em>Originally published at </em><a href="https://blog.learntotaljs.com/posts/2272992001mo71b/"><em>https://blog.learntotaljs.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838110ec5121" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>