Tech Junkie Blog - Real World Tutorials, Happy Coding!: AngularJS SPA: Building The Bank Application JavaScript Objects (Business Entities)

Wednesday, January 9, 2019

AngularJS SPA: Building The Bank Application JavaScript Objects (Business Entities)

Up until this point all we did was take care of the plumbing, MongoDB for the database, AngularJS as the application framework, expressJS for hosting, and Heroku as deployment infrastructure in the cloud. Whew! It feels like I am spitting out development hastags and buzzwords.  But, you know what they always say "it takes a village to build a SPA application".  Well they didn't say that, but they should! Who are they anyways?  The software engineer gods?  Or god forbid the mythical "full stack developers!!  Fear them the full stack developers!  But I don't know who they are, you ask.  Well they are just awesome! God says.  They are 10x!  Wow 10x, you said to yourself.  They must be good!  Hahaha  I just love the buzzwords.  It's entertaining.  I would never say I am a full stack developer.  I am just a developer who knows a lot of stuff.

In this post we are going to take a step back and start working on the actual application and take the plumbing out of the equation for a while.

As with any application at the center of it all is the question.  What does the application do?
Since our application is banking application, we will create objects that are in the banking domain.  This is called a domain driven design.  We are not going to follow the domain driven design (DDD) to a T, but we will follow the spirit of it.



First things first, we need a bank.  Follow the steps below to create the bank object.

  1. Open the "ACMEBank" application with your favorite IDE
  2. Add the file bank.js to the models folder 











3. Add an IFFE to the file

(function () {
}());

4. Now let's create the bank object

(function () {
    function Bank(name, user) {
        this.Name = name;
        this.User= user;
    }
}());

You might be wondering why we created the Bank object with a function.  The reason we did that is because we basically created a constructor that we initiate with constructor arguments. The object has two properties, the name of the bank and the user that is accessing the application. Now I could create another file to create a user object but since it's such a simple object I am going to put it in the same file as the bank.js file. The User object just contains the name of the user and the accounts that belongs to the user.

Here is the code to create the User object

(function () {
    function User(name, accounts) {
        this.Name = name;
        this.Accounts = accounts;
    }

    function Bank(name, user) {
        this.Name = name;
        this.User= user;
    }
}());

5. Now it's time to create the account object, create a file call account.js in the models folder.
(function () {
    function Account(balance, type) {
        this.balance = balance;
        this.type = type;
    }

    Account.prototype.deposit = function (d) {

        this.balance = this.balance + d;
        return this.balance;
    }

    Account.prototype.withdrawal = function (w) {
        this.balance = this.balance - w;
        return this.balance;
    }
}());

The account object basically has the balance, and type properties as well as the deposit and withdrawal method in it's prototype. If you need more information on JavaScript prototypes you visit this post.

Now lets say we have another kind of account class which is the Premium (high earners) account class this class can make withdrawal, and deposit like the regular account.  But it can do more like transfer to another account.  Also it pays a 5% bonus on the balance every time he/she makes a deposit or on account creation.  Even though this is probably way too generous, I just wanted to simulate a business rule that you might encounter in real life.  Therefore, programmatically we want to inherit from the base class which in this case is the Account class. This is how we would inherit from the Account class and build a Premium class.  First let's create the "inherits" function which will inherit the prototype object from the Account class to the Premium class.


        function inherits(baseClass, childClass) {
            childClass.prototype = Object.create(baseClass.prototype);
        }

As you can see its not really a real inheritance, it's more of a simulation of an inheritance.  We cloned or copy the prototype object of the Account class, which in this case is the base class.  Think of the base class the original copy, and Premium class the clone.  But the clone can have it's own methods after it has been cloned.  Kind of like the T1000 in Terminator.

Now let's create the Premium class

        function Premium(balance,type) {
            this.balance = balance + (balance*.05);
            this.type = type;
        }

As you can see the T1000, I mean the Premium class has it's own way of figuring out the balance with a 5% bonus.

Now let's call the "inherits" function to inherit from the Account class.

        inherits(Account, Premium);

Now that we inherited from the Account class we are going to add the "transfer" function that is exclusive to the Premium class

        Premium.prototype.transfer = function (from, to, amount) {
            from.balance -= amount;
            to.balance += amount;
        }

In its current state the deposit function does not add the 5% to the deposit because it's using the Account's inherited functions.  To get the correct balance for the Premium class we can override the deposit and function.  Like this

        Premium.prototype.deposit = function (d) {
            this.balance = this.balance + d;
            this.balance = this.balance + (this.balance * .05);
            return this.balance;

        }

Here is the full code for the account.js file

(function () {
    function Account(balance, type) {
        this.balance = balance;
        this.type = type;
    }

    Account.prototype.deposit = function (d) {

        this.balance = this.balance + d;
        return this.balance;
    }

    Account.prototype.withdrawal = function (w) {
        this.balance = this.balance - w;
        return this.balance;
    }


    function inherits(baseClass, childClass) {
        childClass.prototype = Object.create(baseClass.prototype);
    }

    function Premium(balance, type) {
        this.balance = balance + (balance * .05);
        this.type = type;
    }


    inherits(Account, Premium);

    Premium.prototype.transfer = function (from, to, amount) {
        from.balance -= amount;
        to.balance += amount;
        from.rebalance();
        to.rebalance();
    }

    Premium.prototype.deposit = function (d) {
        this.balance = this.balance + d;
        this.balance = this.balance + (this.balance * .05);
        return this.balance;

    }
    Premium.prototype.rebalance = function()
    {
       this.balance +=  this.balance * .05;
    }
}());

Note: I've added the rebalance prototype method to the Premium object as another way to resolve the %5 bonus for the Premium deposits. You can learn more about JavaScript inheritance in this post.

Your models folder should look like this













Similar Posts:

Previous: AngularJS SPA: Install RoboMongo GUI for MongoDB

16 comments:

  1. It’s amazing how interesting it is, My first visit made me very happy. Thanks bank al habib car loan | best mutual funds in pakistan

    ReplyDelete
  2. I think a good place to start for a newcomer is with a Swedish Massage and a facial. These are still the most favorite spa treatments because people love them. Although there are many wonderful treatments on most spa's menus, such as hot stone massage, Ayruvedic treatments or even body scrubs and wraps, I would not recommend them for the first time spa-goer.full body massage

    ReplyDelete
  3. Thank you for posting this, this is very powerful! sir RNkhabri

    ReplyDelete
  4. Oferecemos os melhores serviços para seguidores, curtidas, comentários e visualizações no Instagram. Os serviços são entregues de forma rápida, segura e por um preço honesto e barato.
    Todos os serviços são iniciados de forma automática e você pode fazer um teste grátis de seguidores, curtidas e visualizações no Instagram.

    O Go Followers surgiu em 2015 e durante alguns anos foi o melhor e maior site para comprar seguidores, curtidas e comentários no instagram. Com o passar dos anos evoluímos e em 2021 lançamos um novo site simples e intuitivo para aumentar a experiência dos mais de 150.000 clientes atendidos.

    Nossa ferramenta envia seguidores brasileiros reais e ativos em sua grande maioria para qualquer perfil do Instagram. Escolha o melhor pacote para comprar seguidores instagram de alta qualidade. Você poderá escolher alguns pacotes como seguidores com curtidas, seguidores masculinos, seguidores femininos e seguidores automáticos.
    Todos os pedidos são feitos de forma automática e iniciam em poucos minutos após a compra, tá esperando o que?

    ReplyDelete
  5. Have you checked your Home Insurance Quotes for better insurance rate quotes lately? Many people ignore this just because they don't want to go through all the troubles looking for insurance rate information or comparing rates, and decide to stick with the old companies which they think have already given them the best rates and coverage even if the rates are raised by the companies. If that is what happen, they might have missed the chance of getting better rates of Car Insurance Quotes and coverage offered by other insurance companies on the market.

    We take into account a variety of factors to pair you with your match. We've worked relentlessly to research all of the top insurance providers and devise a matchmaking system that finds the company (or companies) most likely to give you the best rate based on your selections. Unlike other quoting tools, that collect your data and spam you with calls, emails and mail, we don't need any form of personal information, such as Name, Phone, Email, or Address, to pair you with your match Auto Insurance Quotes.

    When comparing the various car insurance quotes you received, you should take the time to look through each coverage option as well for Health Insurance Quotes. Never make it a habit just to look at the price of the coverage, because the coverage options and features will be different. When you apply for quotes, it is important to provide the same information to all the insurance companies Life Insurance Quotes. If you give different information to the different companies, your quotes will be biased and there is no point in comparing the quotes. During the comparison of Small Business Insurance Quotes, you should wait till you receive all your quotes before making a decision, because you never knew which company would provide you the best deal. If one company provides you the most coverage at the best price, you know exactly whom to go with Pet Insurance Quotes.

    When comparing Renters Insurance Quotes, be sure to check off all the pros and cons. Shopping around is definitely easiest online.

    ReplyDelete
  6. Garuda999 adalah sebuah agen casino online yang merupakan mitra salah satu bandar judi online24jam internasional terbesar di Asia, SBobet, yang berpusat di Filipina. Sebagai salah satu mitra penyedia layanan judi online terbesar, tentunya kami juga berkomitmen untuk memberikan layanan terbaik bagi pengguna kami, yaitu penggemar judi online Indonesia. judi slot game, slot online nexus, slot online casino, slot online 88, slot online idn, bandar togel idn, judi bola pulsa, casino online terbesar di dunia, bandar togel pasaran terbaik, judi bola 777, situs judi bola yang ada promo bonus 100, judi bola 828, casino online game, judi bola depo pulsa, situs judi bola freebet, situs judi online poker yang banyak bonus, judi online live, judi poker deposit pakai pulsa 5000 Dengan adanya aturan yang berlaku di Indonesia, kami menyadari jika banyak penggemar judi online di Indonesia, yang kesulitan untuk mendapatkan layanan yang berkualitas. Sehingga untuk itulah kami, Garuda 999 hadir sebagai agen casino yang terpercaya, untuk melayani penggemar judi online di Indonesia, tanpa bertentangan dengan aturan yang berlaku. Karena sebagai mitra yang mematuhi aturan, kami beroperasi dari Manila, Filipina, sebagaimana mitra induk kami. Dengan demkian penggemar judi online di Indonesia, dapat dengan mudah mengakses layanan judi online, yang kami sediakan dan merasakan kesenangan bermain judi online dengan aman dan nyaman, selayaknya bermain pada casino online bertaraf internasional. judi bola aman, Judi Slot terlengkap, master judi bola 99, qq slot online freebet,judi online poker sampoerna, slot online indonesia terpercaya, slot online game, situs judi bola eropa, bandar togel kamboja, judi bola 168, slot online judi, peraturan judi bola 90 menit, 9 poker, casino online paypal, judi bola deposit pulsa, judi bola adalah casino online di indonesia, bandar togel tertua dan aman, casino online malaysia, judi bola mix parlay, bandar, togel onlen, casino online terbaru. Sebagai agen casino online mitra dari SBobet, yang merupakan salah satu agen bola Euro2021 terbesar di Asia, tentunya Garuda 999 juga membuka peluang bagi penggemar taruhan olah raga khususnya sepak bola, di tanah air, untuk ikut meramaikan even sepak bola dunia tersebut. Dengan didukung oleh sistem sports book handal yang disediakan oleh SBobet, penggemar taruhan sepak bola di Indonesia - Judi Online, tidak perlu khawatir untuk ketinggalan bertaruh pada even besar tersebut. Karena sistem sports book yang kami adopsi dari mitra induk kami, merupakan salah satu yang terbaik di dunia, yang dapat melayani taruhan sesuai jadwal pertandingan pada Euro 2021 secara real time - Judi Slot.

    ReplyDelete
  7. Ob Schmutz, hartnäckiger Belag, Schimmel, Vogelkot, Bakterien, Dreck, Staub oder unangenehme Gerüche, bei unserer Gebäudereinigung Hannover erwartet Sie ein glänzendes Ergebnis. Die Firma Immoclean reinigt Gebäude unterschiedlichster Art wie Schulen, Kindergarten, Arztpraxis, Altersheim, Museum, Disko, Hallen, Krankenhaus, Hotel, Baustelle, Restaurant, Kaufhaus, Supermarkt - Unterhaltungsreinigung Hannover.

    Vertrauen Sie dabei unserer Erfahrung, den vielen Referenzen und einer Kundenzufriedenheitsgarantie. Zuverlässigkeit und Qualität sowie eine absolut hygienische Reinigung können wir Dank unseren geschulten und mit modernstem Reinigungsequipment ausgestatteten Mitarbeitern gewährleisten - Broreinigung Hannover. In einer umfassenden und persönlichen Beratung erstellen wir sowohl für Klein- als auch Großkunden einen persönlichen Reinigungsplan ganz nach Ihren Wünschen. Bei Immoclean aus Hannover, der Nummer 1 unter den Reinigungsdiensten, Gebudereinigung hannover ist Ihre Firma oder Unternehmen in guten Händen. Vereinbaren Sie noch heute einen Termin mit unserem Reinigungsunternehmen, wir freuen sich auf Sie - Praxisreinigung Hannover!

    ReplyDelete
  8. In the event that you are a user of Brother printer at your home or workspace and looking for the right direction to interface it to Wifi then today you have arrived at the opportune spot. Connect brother printer mfc l2750Dw to wifi We, Tech Support Expert is the best outsider specialized network that is master in tackling all your printer issues. Our network has a group of multi-gifted and talented specialized experts who give lasting setup and extraordinary exhortation users. In this blog area, we are here with the answer for brother Printer not Connecting to WiFi issue

    ReplyDelete
  9. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up
    Regards : Plumber in clapham

    ReplyDelete
  10. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. Gebäudereinigung Hardegsen

    ReplyDelete
  11. I am able to provides you with the objective In this article understand the best way to practice it the right way. Understand in addition to generate anything beneficial. glock 35 mos

    ReplyDelete
  12. Archipelago Learning ialah agen bola terpercaya yang mempunyai daftar bandar bola resmi, pelayanan situs terbaik dan selalu memberikan keuntungan promo terbesar di ...

    ReplyDelete
  13. DAFTAR 6 situs judi online TERPERCAYA 2021 · 1. Slot Online Pragmatic Play · 2. Slot Online Joker123 · 3. Slot Online Playtech · 4. Slot Online PGSoft · 5. Slot ...

    ReplyDelete
  14. There are in any case, a few kinds of building projects that may likewise be dependent upon different sorts of legal necessities and assents so you should ensure that you remember this.
    Tree Cutting Pearland

    ReplyDelete
  15. Eliminate the cleaning agent from your skin with the lukewarm water in your plastic bowl. HydraPeel

    ReplyDelete

Search This Blog