<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Francis Gyimah</title>
    <description>The latest articles on DEV Community by Francis Gyimah (@fgyimah).</description>
    <link>https://dev.to/fgyimah</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F193320%2F290baf85-a87f-42ca-b811-08de7ece811c.jpg</url>
      <title>DEV Community: Francis Gyimah</title>
      <link>https://dev.to/fgyimah</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fgyimah"/>
    <language>en</language>
    <item>
      <title>Express with TypeScript and TypeOrm. Part 2</title>
      <dc:creator>Francis Gyimah</dc:creator>
      <pubDate>Mon, 27 Apr 2020 14:04:57 +0000</pubDate>
      <link>https://dev.to/fgyimah/express-with-typescript-and-typeorm-part-2-57a2</link>
      <guid>https://dev.to/fgyimah/express-with-typescript-and-typeorm-part-2-57a2</guid>
      <description>&lt;p&gt;In the first part of this &lt;a href="https://fgyimah.netlify.app/posts/express-with-typescript-and-typeorm-part-1-1mej/"&gt;tutorial&lt;/a&gt;, we discovered how to set up a base express typescript application. In this part, we will look at how to set up environment variables, which is a great way of storing sensitive information like API keys. This is a special file ending with the .env extension that is excluded from git so as to not expose your sensitive file to the world.&lt;/p&gt;

&lt;p&gt;To begin with, we install a special library called dotenv that is able to read from this file and make it available to the server via process.env.* We install this library by typing in our console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save dotenv
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Dotenv ships with its own types so there is no need to create one ourselves. We configure dotenv in our application by adding the following line on top of our index.ts file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'dotenv/config';
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Our index.ts file should now look like the following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'dotenv/config';
import * as express from 'express';

const app = express();

//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) =&amp;gt; {
  res.status(200).json({
    hello: 'World!',
  });
});

const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () =&amp;gt; {
  await app.listen(port, () =&amp;gt; {
    console.log(`
Server running on http://localhost:${port}
`);
  });
};

startServer();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This configures our application to read from the .env file, which is yet to be created. In the root of your application, create a new file called .env. To test, we add a port variable and change it to 7777 as shown&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PORT=7777
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;After restarting our server, we see our application is now running on port 7777 other than the 3000 from the previous tutorial. We proceed to set up our database. &lt;/p&gt;

&lt;p&gt;\&lt;br&gt;
We install typeorm library by typing&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save typeorm pg
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;TypeOrm just like dotenv also ships with its own types as it is developed in typescript, the pg library helps typeorm connect to our database which is PostgreSQL in this case. In the root of our application, we create a file called ormconfig.json, this file will be used by typeorm to connect to the database. We specify the database configuration as follows, feel free to change and put ur own values inside&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "postgres",
  "database": "express_typescript",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entities/**/*.ts", "dist/entities/**/*.js"]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Make sure to create the database first using either the psql shell or any gui tool of your choice. The file also specifies that all our database entities will be in the entities folder inside the src file, or inside the entities in the dist folder after the typescript is transpiled. &lt;br&gt;
The synchronize: true, tells TypeOrm to use our entities to create tables inside the specified database. This is very helpful as we get to create tables and interact with the database directly in typescript without actually touching any SQL code.&lt;/p&gt;

&lt;p&gt;We then create a ts file called database.ts to use to establish the connection. We add the following code to it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createConnection } from 'typeorm';

export const connectDB = async () =&amp;gt; {
  await createConnection();
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We finally let our main index.ts file know of this so a connection can be made to the database. We import it inside the index.ts and run it, our index.ts file should finally look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'dotenv/config';
import * as express from 'express';
import { connectDB } from './database'

const app = express();

//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) =&amp;gt; {
  res.status(200).json({
    hello: 'World!',
  });
});

const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () =&amp;gt; {
  await app.listen(port, () =&amp;gt; {
    console.log(`
Server running on http://localhost:${port}
`);
  });
};

(async () =&amp;gt; {
   await connectDB();
   await startServer();
})();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That is it, run your server with npm run start:dev and see some database log information meaning a successful connection has been made to the database. Read more about TypeOrm &lt;a href="https://typeorm.io/"&gt;here&lt;/a&gt;.Thanks for reading and don’t forget to share.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>node</category>
      <category>express</category>
      <category>postgres</category>
    </item>
    <item>
      <title>Express with TypeScript and TypeOrm. Part 1</title>
      <dc:creator>Francis Gyimah</dc:creator>
      <pubDate>Sat, 25 Apr 2020 11:15:53 +0000</pubDate>
      <link>https://dev.to/fgyimah/express-with-typescript-and-typeorm-part-1-1mej</link>
      <guid>https://dev.to/fgyimah/express-with-typescript-and-typeorm-part-1-1mej</guid>
      <description>&lt;p&gt;Setting up an express server with TypeScript can be daunting at first. In the first part of this 2-part series, we will look at how to set up a professional express TypeScript project from scratch. We will set up the base folder structure and also the base express setup. We will then look at how to connect to our database(PostgreSQL) in this case in the second part. Let's begin.&lt;/p&gt;

&lt;p&gt;To set up an express project you need to have nodeJS installed locally on your machine, this can be downloaded from &lt;a href="https://nodejs.org"&gt;here&lt;/a&gt;. This also gives you access to a very important CLI tool called NPM (Node Package Manager). Using NPM we can add packages from the NPM registry into our project.&lt;/p&gt;

&lt;p&gt;Verify that NodeJS is installed on your machine by typing&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node --version
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;A version should be printed indicating NodeJS is successfully installed on your computer.&lt;/p&gt;

&lt;p&gt;We create an empty directory that will hold all of our project’s code. I’m going to name mine express-typescript but feel free to use whichever name you want.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir express-typescript &amp;amp;&amp;amp; cd express-typescript
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Inside this folder, we initialize a new npm project by typing&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The -y flag is to tell NPM to give us the default configuration. We then install express as well as the types for express and the typescript compiler along with other helper libraries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save express 
npm install --save-dev @types/node @types/express typescript nodemon ts-node
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Typescript is what helps our application transpile the typescript programming language into JavaScript. Ts-node allows us to run typescript files directly without having to transpile them first, this is great for development mode. Nodemon automatically watches for changes within our project and restarts the server without having to do that manually.&lt;/p&gt;

&lt;p&gt;Next off, we’ll create a tsconfig.json file to tell the typescript compiler how to compile our code. We add the following options into the tsconfig.json file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "moduleResolution": "node",
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

    //add decorator support
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "include": ["./src/**/*.tsx", "./src/**/*.ts"],
  "exclude": ["node_modules"]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We modify our package.json with the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "express-typescript",
  "version": "1.0.0",
  "description": "Typescript with express tutorial",
  "main": "index.ts",
  "author": "Francis Gyimah &amp;lt;fgyimah883@gmail.com&amp;gt;",
  "license": "MIT",
  "private": false,
  "scripts": {
    "start": "node ./dist/index.js",
    "start:dev": "nodemon",
    "build": "tsc"
  },
  "dependencies": {
    "express": "^4.17.1",
  },
  "devDependencies": {
    "@types/express": "^4.17.6",
    "@types/node": "^13.13.0",
    "nodemon": "^2.0.3",
    "ts-node": "^8.8.2",
    "typescript": "^3.8.3"
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We have included 3 scripts into our server and these are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  start: This is to tell how we want to start our server in production mode, the compiled javascript will be in the dist folder and we are telling node to run our javascript file from there&lt;/li&gt;
&lt;li&gt;  start:dev: This is how we start our development server, by default, nodemon will look for a file called nodemon.json to run whenever this command is called. We’ll create that in the next step&lt;/li&gt;
&lt;li&gt;  build: this is how we build or transpile our TypeScript code into JavaScript using the tsc command, which we get as a result of installing the typescript dependency.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To configure nodemon we create another file in the root directory of our project called nodemon.json, and add the following code to it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "watch": ["./src/**/*", ".env"],
  "ext": "ts",
  "exec": "ts-node ./src/index.ts"
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;This tells nodemon to watch for changes in the src directory, where our actual code is going to live and also watch the .env file, which is a special file where all our sensitive information like API keys is going to live. We also watch all files with the .ts extension, meaning all typescript files in the src folder. The exec tells nodemon the command to run which is ts-node command and our main script is the index.ts file inside the src folder.&lt;/p&gt;

&lt;p&gt;We create the src folder and the index.ts file in it&lt;/p&gt;

&lt;p&gt;We create a base express server using the following code snippet&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as express from 'express';

const app = express();

//configure application routes
//@GET - dummy api route
//@ts-ignore
app.get('/api', (req, res, next) =&amp;gt; {
  res.status(200).json({
    hello: 'World!',
  });
});

const port: Number = Number(process.env.PORT) || 3000;
const startServer = async () =&amp;gt; {
  await app.listen(port, () =&amp;gt; {
    console.log(`Server running on http://localhost:${port}`);
  });
};

startServer();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;That’s it, we now run the following command in the terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start:dev
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;and go to &lt;a href="https://localhost:3000/api"&gt;https://localhost:3000/api&lt;/a&gt; to see our result. &lt;/p&gt;

&lt;p&gt;In the next part, we’ll look at configuring environment variables and how to connect to a PostgreSQL database  using &lt;a href="https://typeorm.io"&gt;typeOrm&lt;/a&gt;&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>node</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
