Build Your First Github Portfolio Project! Unit Tested, Documented, Typescript Package

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video you'll set up a typescript project from scratch you'll use yes link and printer to speed up development automatures and formatting you set up unit tests with chests add documentation and developer endos with jsdoc you'll also learn the secret as to why open source projects are used and others are completely ignored by the end of this video you'll have written a resume ready typestream package you learn about unit tests documentation and you'll have written a readme that makes your career pay attention are you ready open up your folder with visual studio code and right click on open in integrated terminal at this point you'll set up a empty package that you're going to initialize with yarn in it and we'll actually go through the steps because we need to customize the entry point so for the name just keep a name that is all lowercase and dash separated and for the description i'll just type a simple ts package used for password generation and verification and for the entry point we'll type lib which means that there's going to be a lib folder we're going to be using and we're going to set that up with typescript in a minute for everything else you can just confirm unless you already have um everything else set up and at this point you're going to have your package.json which means that we can install typescript by typing yarn add typescript space dash uppercase d which means in as a developer dependency in order to use typescript uh you have to pass a configuration file which is called ts config and in this case tsconfig.json so right click here in the file explorer and type new file and create a new file called tsconfig.json you could also initialize it by using a command called tsc-init and i go over that in a separate video if you want me to show you every single line of configuration from typescript that said uh for our setup we're actually gonna have a very straightforward setup that is gonna use the src folder it's gonna ignore the node modules it's gonna output to the lib folder and it's gonna target ecommerce script five since this is a json file you're gonna have a object and the first key we'll use is going to be called compiler options we'll set the out there which is the output directory to dot slash lib then we'll set allow js to be true and we'll do that just in case if we have any javascript file then we're going to target ecmascript 5 by typing es5 on line 6 these are our compiler options we'll add a comma and then we'll have a new key called include which means the uh projects or the folders that we want to actually compile through our compiler for typescript compiler we'll have a list and the only element in the list will be dot slash src a folder called src which we'll create in a second and then we'll add a new comma and on a new line we'll have the exclude option that allows to exclude certain folders in our case we want to exclude dot slash node underscore modules as uh those are already compiled at this point let's add the build command to the package.json so click on package.json and here after line seven after the license type go to new line and type double quotes scripts then have an object remember your line 10 to add a comma because uh you know these are comma separated entries and the script will add will be the build command or the build script and the only thing that the build script will do will be calling tsc and tsc is the typescript compiler so at this point we could test that out but we still don't have an src folder so before we test that out let's uh create that so right click new folder src and then create a file called index dot ts and in index.ts let's declare a variable called the answer set it to 42 and then let's export default the answer you can now compile this code by typing in the terminal yarn build and what's going to happen if you look up on the left is that now we have a new folder called lib that contains a file called index.js and this file is the transpiled version of index.ts next up before we get into coding let's add eslint so that our code can probably be formatted and linted if you're using visual studio code make sure to install the visual studio eslint extension by dirk bomber this extension can also be set up to update the file on save and i'm gonna have a separate video that shows you how to set that up at this point to set up eslint we could use the interactive setup or we can just go through the docs and figure out how that setup works so instead of doing that we're just gonna use a preset built by airbnb and ported over to work with typescript this preset is also used when coding the front end so now you have one size fit all solution for your linting needs and we can install this in one quick swoop by typing yarn add eslint and then pre-tier and then eslint dash config airbnb dash typescript dash prettier and again with dash uppercase d which means development as a development dependency but with one command we're now installing yes lint prettier and is weirdly named thingy which is basically a typescript preset that uses airbnb in order to set that up we'll need to create a new file called eslintors.json so let me show you how to do that we're going to go in the root folder create a new file and type dot eslintrc.json make sure there's a dot at the beginning and the only thing we need to do here since we're working off of a preset is we're going to have since it's a json file we're going to export an object and the only key we'll export is called extends and we'll extend a preset called airbnb typescript dash prettier which we just installed right now and that now means that uh we don't have to go through and configure every single rule and configure all the setup we have most of the brilliance mind from airbnb setting up our preset for us and in order to get that to work we also need to go in the package.json and what we need to do is we want to add a new command after build so comma newline and we'll add a command called lint and this command we'll call eslint on src slash dot which means on the src folder and we're going to target exclusively the dosh the extension type script which can we can specify by typing dash dash etx ts which means dash dash extension type script at this point we have a command and visual studio code should actually pick that up so if i open up src index.ts i should actually start seeing some errors if you do not see any error you may have to just restart visual studio code so i'm going to do that and at this point if i open up index.ts you can see that i'm seeing a bunch of squiggly red lines and that's because all of these are breaking some linting rules and in this case i'm not using the semicolon and in this case again i have i need to add a semicolon so the way you can fix this is by typing command shift p if you're using a mac or ctrl shift p if you're on windows and then you can find the command called eslint fix all auto fixable problems and if you just run this command which you can do you know in a second by typing command shift p enter most of the time you'll actually have eslint basically fix the errors for you and uh that's going to be very convenient especially if you set it to always run on save and by doing that you're going to prevent a lot of potential injuries in the future such as chronic pain and you're also just going to have code that is more cohesive with the rest of the code base let's add the code to handle password hashing and salting we can get this code by looking at the next.js examples repo which i personally highly recommend and you can find that under github slash versailles next js slash blob slash cannery examples and the specific example we're looking at is called with passport and we're in the file called slash lib user.js and if you look at this file you you can see here on line 11 to line 30. we have a method called create user which as you see in the comment we will need to add some sort of database functionality but fundamentally what this uh function does is it generates a random salt which you can think of as a random string and then given this random salt it generates a hash which is derived from the plain text password the salt and then using this particular algorithm and then here on line 40 to line 46 you see this method called validate password which fundamentally verifies that the given input password matches with the user.salt and the user dot hash i.e the actual hashed password so we can take this code change it a little bit and basically we can write our own package let's do that by opening up visual studio code under src create a new file called password dot ts and if you look at the next.js example at the top here online one we have import crypto from crypto which is a native library from node.js so we can just uh assume that we can also import it so we're gonna go on line one import crypto from crypto and as soon as you save and you land you'll see that crypto is actually not available and you'll see this error message cannot find module crypto or its corresponding type decorations and that's because typescript doesn't know in which development environment we are so we need to tell typescript that this global crypto variable is available by adding it as a type and the way you can do that is by going in the terminal and typing yarn add at types slash node and then dash uppercase d for a development dependency if you do that you'll still have an error because crypto is not a default export and instead we're going to be importing random bytes and you can see the intellisense uh coming up and we'll also import pbkdf2sync it's a tongue twister and we're gonna import these two functions from the crypto package at this point we can write our function to validate a password and our function to generate a password now the code should work so let's try it out by writing a function to validate the password so type export cons to validate password this function will receive three parameters the input password the salt and the stored hash and all of these three will have a type of string so after each of them type column space string the return type will be boolean and what we're going to do in this function is we're going to generate the input hash from our encryption algorithm so type const input hash equals to pbkdf2sync which will receive the input password you will receive the salt it will go for a thousand iterations it will have a length of 64 and it will use the digest set to shop five one two and what we're going to do to this we're going to string it with the hexadecimal encoding and then what we're going to do with the input ash is we're going to compare it to the store dash so we can return stored hash triple equals to the input ash so if they match we're gonna have a true result otherwise we're gonna have false you can see that once i save and the linter sets up it actually tells me that it prefers a default export we're gonna ignore that error because we're about to write a second method down here so let's go on line 19 and type export const hash password which will receive the password set to a string and the return value will actually be an object which will have a key of hash which is going to be a string and a second key of salt which is going to be a string as well so let's write that we're going to generate this salt by typing const salt equals to random bytes which will receive a parameter of 16 and then we're gonna call two string hex it's gonna be hexadecimal and then we're gonna generate the hash by typing const hash equals to pbkdf2sync with the password the salt going through a thousand iterations with a length of 64 and a digest of shot five one two and again we're gonna to string it to a hexadecimal encoding we're gonna then return an object with a key of hash and a key of salt there we go and as you can see the preferred default export error goes off at this point we wrote this functionality that we basically scraped off of the internet so we don't even know if it works we're gonna actually have to test that out next now that we wrote our code it's a great time to test that out and the first step to test it out would be to build but since we're gonna be doing a quick test with node.js we also want to make sure we can access the function validate password and hash password from our root of the our package which we can do by going in index.ts and down here on line 4 you can type export star from dot slash password dot slash password this means that typescript will go through the password file and it will export everything that is exported from it automatically which means that now we can require our files uh by just importing the package instead of having to go inside of the specific file let's try that out by going in the terminal type yarn build and now the project is compiled you can see we have the two files in lib in the lib folder and we can test that out by running a node you can literally just type node to enter the node cli and we're going to try requiring these functions so type const curly braces validate password comma space hash password is going to be equal to require off dot and we can do use required dot because we already set our uh main uh to the lib folder and that means that if we type hash password you can see below that you actually get the word function hash password because it's been recognized and imported properly so let's try hashing the password of uh you know my top secret password i get back this object with a key of dash and a key of salt since we want to test this out we want to know that this is actually a consistent process and that the validation also works we're gonna get this object right here and uh create a new file by typing command n or control n on windows paste that and then save it and i'll save it as example.txt and i'll just move it off to the root folder this way we have a couple of uh we just have an example that we can use and this is a great opportunity to actually use jest in order to set up unit tests to verify that our function works as expected let's install jest typescript jest which is a preset for getting it to work with tyscript as well as type slash jest so the typescript knows what's going on go in the terminal and type yarn add jest ts dash jest and lastly at types slash jest use the d modifier for a development dependency then you can set up a the jest configuration file in the root folder by creating a new file called jest.config.json and it's going to export an object and this object will have a key of preset set to ts chest and it will have another key called test environment which will set to node because we're using a node package then we need to set up a script to run our test go in the package.json after lint add a comma new line test and set that to just we'll simply call just and just will figure it out for us and finally we can write our test files right let's set up our first test with jest go in the src folder right click and create a new file called password.test.ts and import the functions we want to test so import curly braces hash password comma space validate password from dot slash password and let's also declare a hard-coded password that we're going to be testing against called const password equals one two three four and at this point when you work with jest you can use describe to wrap tests by topics in this case the function names and then we can use the test function to define each test we want to run and then instead of a test we're gonna run what is called an expat and then we're going to use a comparison function to compare those values so let's go through one example i'm going to write describe the set of tests that i'm going to apply to the hash password this is what we will call the test suite then i'm going to have a function inside of my describe test suite and i'm going to have my first test literally i'll type test the first parameter will be a string in this case ash password returns and object with ash so we want to verify that the function returns an object that contains the key called hash and we're gonna have a function here on line seven we're gonna uh get a result by typing const result equals to ash password with the parameter password and then we're gonna run our test on the password so we're gonna expect result and then we're gonna put a dot here and you can see that you have a bunch of these matchers or uh you know specific ways to compare your result which is here on the left versus what you would expect so in our case we're gonna have a dot to have property and we want to have a property called hash so now we run our first test here line six inside of our first test suite which is called the hash password let's add a second test to it called test this time will be ash password returns and object with salt and this time again we're going to get the result with password of password and then we're going to check by running an expect we're going to expect the result dot to have property and this time the property needs to be sold so this point we wrote a couple of tests inside of our test suite and we can run them by using yarn test i'm seeing a warning there's probably a typo in the just config with test environment you can fix it by fixing the typo and you can see that the tests are passing and specifically what you can see is that you have the test suite name hash password which comes from the described statement on line 5 and then you have specific names of tests with their corresponding result here which are defined by using the test function now it's time to test out our validate password function in order to do that we need the values that we already have from our example so i'm going to copy this and i'll add them to a object called const values and i'm also going to add a couple of keys here i'll add a key called string which uh we used one two three four and then i'm also gonna have a key of wrong string set to admin one two three four basically i'm gonna have a proper password i expect the test to pass with and the wrong password i'm gonna create a new set of tests a new test suite by tapping describe and this time we're going to call it validate password because that's the function we're testing and then we're going to have a test we've correct password and what we're going to do here is we're going to expect and here we're gonna call validate password we're gonna pass the values dot string then we're gonna pass the values dot salt and then the values dot hash and what we're going to do is we're going to expect this dot 2 b set to true so we expect this test to pass and then we're going to have a similar test with the wrong password so let's type test with wrong password where again we're going to have our function we're going to expect and this time we're going to expect validate password with values.wrong string and then values dot salt and lastly values dot hash and again we're going to expect them dot to be false we expect this to not be the correct password we can run the test with yarn test and you can see that we have our test suite passing and uh four tests are passing congratulations you were able to write your hashing and verifying functions and you were able to also unit test them that's uh better than 99 of developers let's go one step beyond by also adding documentation we can enrich the documentation by adding description types and return values and we can do that by using a very common format called js doc and if you're using visual studio code you can go at the top of a method such as validate password then type slash star star and then press enter and you can see that intellisense will autocomplete that for you when you're working with jsdoc you basically are gonna have a bunch of directives and in this case the directives we're interested in are gonna be the param and the returns where the param represents something that you put in the function and then the returns specifies what you get back we can also have our description up here at the beginning and there are also other directors which you can look into the jsdoc documentation so let's add our documentation we're going to type given and input password assault and and hash thus the given password match with the hash and let's also add types here so you can specify types by adding curly braces and then the name of the type before the name of the parameter and in this case they're all strings and lastly we're going to return and what we're going to return is going to be a boolean and we'll also have a description which will be those hash of input password plus salt triple equals to stored hash which is basically what we're doing let's add documentation for hash password and since we have a return type that is complex basically we return an object we could just be content with returning an object in our documentation but we can actually specify what is called a type dev which allows us to specify complex objects so let's do star star and i'll delete everything and here i'll type at type def curly braces object which because it's a type object and we'll call it ash and salt and then we'll type at property which is going to be a string it's going to be hash this is the hash we got and then the other property again a string will be the salt the salt used for hashing so now that we have this type def we can actually use it with our jstoc here on line 33. type slash star star and then press enter and you'll have the autocomplete and what we're going to do up here we're going to type given a password hash it with assault then return the hash and the salt now the parameter would be a password of type string there's no reason to have a description password is self-evident and then in the case of the returns parameter we'll add again this custom type hash and salt which we defined up here as a typedef and then we're just going to add some descriptions such as object containing the ash and the salt used containing so now we are basically made the documentation as complete as possible and the reason why i really like jsdoc is because when used properly you can understand the method without even having to read the body you can just look at the function signature which is something you may want to do especially when you're dealing with complex projects you want to literally hide the function body and just look at the signatures because that way you don't have to tax your brain you can just focus on using these as black boxes and again this is great especially when you're working with a team at this point we can use the library called jsdoc to turn the comments into actual documentation that we can hand off to other developers in the team so let's go ahead and do that to add jsdoc we first need to install it and then we need to set it up and then add a script just like every other tool we installed so open up the terminal and install js dock by tapping yarn add js dock or lower case and then use dash d because it's a development dependency as well next let's create a file called dot json so on the right type a new file dot jsdoc.json and this is going to be a little clunky because js dock is a little older than these newer tools that basically have everything configured for you so we have to be a little more explicit we're going to create an object the first key will be called source and it will receive an object called we have a few keys the first one being include which allows us to specify what we're going to be using to generate our documentation and in this case we'll use the dot slash label we're going to use the libra the lib folder i.e the comp the transpiled version of our code then we'll use an include pattern which allows to specify which files we're going to be using and basically we'll be using the js files without the test files so let's type dot and this is uh regex if you are intimidated by this don't worry about it you can scrape it off of the js documentation but again this is regex so let's type dot plus slash slash or backward slash backwards dot js and then we'll type doc a pipe x and then a question mark and a dollar sign and then we'll have an exclude pattern which will be quite literally the same but it's going to be for test so we'll type dot plus back back slash twice then test.js open parenthesis doc type x question mark dollar sign so this means the stuff that we're going to be using next up let's set up the source type set to module because uh we want to treat the code like that then we're going to have tags and this is the way jsdoc parser will parse our tags and we'll just use the default tags so let's set up all unknown tags set to true this means it's going to pick up stuff that it doesn't necessarily recognize and then we'll also add the dictionaries set to a list and we'll use jsdoc and closure next we're going to use templates settings for the template i will use clever links set to false and then mono space links and the s and mono spaces lower case set to false and lastly we'll have a last key called opts which is basic options and we'll type destination because we need to specify the destination folder and we'll use dot slash docs so we'll use a new folder called docs so that's where our documentation will go let's go on the package.json to set up our script so after line 11 type a comma new line doc we'll first compile our code by typing tsc you could also do build but that's fine tsc and then we'll do end end js doc dash c and then dot slash dot js doc dot json where dot c is the configuration file and we specify in the path to the configuration file from the package.json and now we can test this out by going in the terminal and typing yarn dock there we go we created our documentation let's open it up you can see that you have a bunch of file fonts script styles etc the simplest way to check this out is to right-click reveal in finder and then opening the index.html and what you're going to see is that now you have everything defined for you so you have global methods one is called ash password which receives a password of type string with the description we wrote and then it also has a return type and you also have the validate password and the beauty of jsdoc is that it literally turns something that takes you a minute to doing code into something that will probably take you weeks if you actually had to write and manage your own documentation so at this point we added jsdoc the last step is to actually write a great readme that is going to catch the attention of people that want to use your package the readme of your package is almost as important as the code and the main reason is that it truly sets the tone for how the external people are going to perceive it whether their potential employer colleagues or people that just want to use your code i want to show you a couple of examples of very good readmes of tools that you probably already use one of them is nodemon the most popular way to restart your server whenever there's a change and you can see that the installation and the usage is as simple as possible and then what the readme tries to do is also go as deep as it can in addressing the most common questions or examples that they can and another amazing example is stripe where stripe i would argue stripe has become the the facto standard for payment processing because their documentation is that good and that's stellar because every single teacher developer etc will just look at the stripe docs see that they're super easy to use and say okay this is the one we're going to use we're not going to use the other options you know because there's no point this is so so much simpler so much more convenient and the readme definitely plays a part in that a couple of notable exceptions are strappy which uh you know just tells you go on the website you know bro come on the website same for creator react app where it literally just says you know click the docs we're not gonna have a readme you just click the doc probably because they're big enough that they can afford to do that but from my experience you want to do quite the opposite you want to have a very rich readme and the tool you could use to do that since we already use js stock you can actually use this mpmgs package called js doctor markdown to basically take the js doctor you have and have it automatically generate markdown for you so that you can have an amazing readme written in just a few seconds and i've had experiences where this package will break sometimes so i'll just uh show you and talk about it and i'll show you how to write a decent readme so first thing we'll do is go on visual studio code and open up the terminal and next we want to build we want to make sure we have already built our project and we have the latest version in our lib folder and then what we'll do is we'll use mpx which is a way to execute packages without downloading them and we'll do mpx js doc js dock dash 2-markdown and then we'll specify the folder which is going to be lib star and what's going to happen is npm will automatically download the package and then it will execute it for us and the beauty of uh what's gonna happen is that as you can see we get this output which is literally markdown that we can use so we can just copy from functions until the bottom here then you can copy this you can then create a new file called readme readme.md all caps paste it and then save and you can use a keyboard shortcut which should be ctrl shift v on windows and command shift v on a mac to open a preview and you can see how you basically have a fully written readme md document markdown document written for you the last thing you will do here at the top you will add a single hashtag to specify a title you will put the name of the package in this case password hashing and then you will write a simple introduction a simple package to hash passwords and verify if the passwords password and the ash match and then you could add a section for installation where you will do the code section by using free backticks and you can type yarn yarn add password hashing and then you perhaps could even do a usage section which would be you know the the overkill version and you can type javascript up here so that you specify that the language that you're using is javascript and you will do something like import validate password and hash password from in this case the name of the package password dash hashing and then you would use it something icons the curly braces ash and salt equal ash password of your password here and then you will verify the password with const is valid equal validate password of your password the salt and the rush right so at this point you written a great readme you basically wrote your own package so the next step would be for you to publish this on github or publish it on npm to publish a package to the npm registry you just got to go on mpmjs.com and you need to have an account when you create the account you're going to set up a username and you're also going to set up a password you need to remember those unfortunately you literally need to remember them because you need to log in locally in your terminal after you have installed npm which if you have node you already have mpm you can type npm login and you'll be asked with your username and your password once you fill those in you'll see that you're able to log in and you're going to be able to push packages on your behalf basically once you did that you can go in the code that we wrote in the package we wrote in this case password hashing and you can type yarn publish and this is basically going to help you bump to a new version and it's also going to help you publish in this case i'm not going to bump 20 version i'll just press enter if the name password dashing was available i would have been able to publish a new package under that name in this case you see could not publish package blah blah blah are you logged in as the correct user and that's because there is already a package called password hashing so what we can do just for this example would be to change the name of the package to something like password hashing entrepreneured so that i know that nobody has uh set that up and i can publish it and you'll see that this will be successful so once you do publish the package you can now find it in npmjs it may take a couple seconds there you go you can see it and now you'll also be able to see the complete readme as we set it up to publish your package to github so that you can either reuse it share it with other developers or collaborate you can go in your own github profile then click on repositories and on the right you'll see the new repository command you can create a new repository in this case i'll call it the password hashing entrepreneured and you can fill this in make sure not to either read me or you're gonna have issues later just to click on create a repository and after you do that you'll see a bunch of commands basically i'll just translate them to you and there's also a separate video i made and there's also going to be an ebook on the most commonly used commands we've get in github in this case we want to initialize the repo with this command get in it we don't need to address we'll skip that then we want to commit with the first commit we want to rename our branch from master to main we want to set the remote to the specific github repo that you set up and then you want to push to origin main so fundamentally we're going to do most of these we're going to do something else as well so let's copy the git init command go in the terminal type get in it to initialize an empty repo and you'll see that basically everything turns to green if you do that yeah you see that basically everything starts to be tracked and what we need to do once we set up a git repo is we need to also set up a new file called dot git ignore which is basically a file that allows us to specify stuff that we don't want to track on github most notably we don't want to track the node modules so on the top of of git ignore type node underscore modules and what you'll see is that once you do that here on the left node modules goes from green to gray because it's no longer being tracked as far as i'm aware we'll keep track of everything else so at this point we can go back in the terminal and after getting it we'll do git status to check what's going on basically we'll see that there's a bunch of stuff that is being tracked i'm seeing also this dot ds store which is a mac os specific file so just add it to the git ignore to ignore it as well next we can literally go in this uh ui commands here that you get with the source control tab of visual studio code and basically you can set up your first commit there so that's that makes life is a lot easier but we can also do it here in the code and we can do it by doing git add dot which means track everything and now everything will be in the commit and then commit with git commit dash m because we're specifying a message in line and this message will be first commit at this point we have all this stuff the next step is to set up our remote so let's go back in google chrome the remote line is here git remote add origin github blah blah so let's add a remote and we're still probably using the master branch which we can verify by typing it branch yeah we're on master so let's rename master to main by using git branch dash upper uppercase main which means again rename master to main and lastly let's push with git push dash u origin main where the dash u means that it's gonna keep track of those changes to our remote so at this point we pushed our code and we can go back on github by refreshing the page and you'll see that the code has been pushed there you also see that readme is nice and ready to be seen so at this point you were able to publish on npm you were able to publish on github fundamentally you wrote a unit tested package with typescript yes lint so that it's written to the highest standards and any person that you know that has alpha brain cell will appreciate the quality of the code that you wrote so yeah let me know what you think and if you have any question use the q a feature so thank you for watching [Music] you
Info
Channel: Alex the Entreprenerd
Views: 1,314
Rating: undefined out of 5
Keywords: strapi, stapijs, strapi.js, strapi.io, strapi notes, strapi course, strapi tutorial, EsLint, TS, Typescript, ST, Ts Coding, Ts Package, Package.json, Git, JsDoc, TS JSDoc EsLint Jest, Jest, JestJS, Jest TS, TS Jest, ts-jest, es-lint, eslint TS, tslint
Id: RnAJNCj0ut0
Channel Id: undefined
Length: 37min 29sec (2249 seconds)
Published: Fri Apr 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.