---
# System prepended metadata

title: Deno & PostgreSQL
tags: [PostgreSQL, deno, web, typeScript]

---

# Deno & PostgreSQL

###### tags: `web` `deno` `typeScript` `PostgreSQL`

[TOC]

## PostgreSQL SetUP 



Create login or group role 

![](https://i.imgur.com/UdUxqZm.png)

Create Database 
![](https://i.imgur.com/u7T5gLy.png)


login or group role property 

![](https://i.imgur.com/PhtzTgg.png)


### Create the table 
Go to the DenoAPI/Schemas/table 


![](https://i.imgur.com/OmUJS6Q.png)


![](https://i.imgur.com/WAvYWoZ.png)

Instanll the denon

[Doucment: denon](https://deno.land/x/denon@2.5.0)

```
deno install -qAf --unstable https://deno.land/x/denon/denon.ts
```

If you get an error it's because your version of deno isn't up to date. A solve way is just to go ahead and run the command 

```
deno upgrade
```

## DENO NIT

```
denon --init
```


```json
{
  "$schema": "https://deno.land/x/denon@2.5.0/schema.json",
  "scripts": {
    "start": {
      "cmd": "deno run --allwo-net server.ts",
    }
  }
}
```

However, with the json file we can add the an array of allow and if we want an environment variable 

```json
"allow": [
        "net",
        "env"
      ],
```
### setting env

```json
 "env":{
        "PORT":"5000"
      }
```

### Add logger 

this instance we could use debug here and set that to true if you want to more information spit out 
```json
  "logger": {
    "debug": true
  }
```


### Global environment variable 

```json
  "env": {
    "TOKEN":"meowhecker "
  },
```
### scripts.json 
```json
{
  "$schema": "https://deno.land/x/denon@2.5.0/schema.json",
  "env": {
    "TOKEN":"meowhecker "
  },
  "scripts": {
    "start": {
      "cmd": "deno run server.ts",
      "allow": [
        "net",
        "env"
      ],
      "env":{
        "PORT":"5000"
      }
    }
  },
  "logger": {
    "debug": true
  }
}
```

Running the script

```
denon start 
```

![](https://i.imgur.com/LW3OAo6.png)


![](https://i.imgur.com/uu7Rt7d.png)


### set the server port from the env variavle 

```typescript
const port = Deno.env.get("PORT") || 5000 
```
""|| 5000" means if he can't find the port from the env variable. he is going to set the value of 5000 with the port number.



## Configure Database 



### DB setting 

```typescript
const DBcredentials= {
    user:"meowhecker",
    database:"denoapi",
    password:"meowhecker",
    localhost:"meowhecker.com",
    port: 5432
}

export{DBcredentials}
```


## Import Client 

add client,DB configure in our controller 

https://deno.land/x/postgres@v0.17.0

Import to the controller/gun.ts

```typescript=
import {DBcredentials} from "../config.ts"
import { Client } from "https://deno.land/x/postgres@v0.17.0/mod.ts";
```


## Initialize Client 


Client allows you to communicate with you postgreSQL database and execute postgreSql statements asynchronously.
```typescript

//Intitialize client
    const client = new Client(DBcredentials)


```
## Extracting  guns

```typescript
 const gunRequest = body.value
```

### Connect to DB

```typescript
 await client.connect()

```
### typescript Adding a gun by uesing the sql command

```typescript
  const result = await client.query("INSERT INTO guns(name,description,price VALUES($1,$2,$3))", 
                    gunRequest.name,
                    gunRequest.description,
                    gunRequest.price) //the second parameter here of waht we want to put in thost money signs in sequential order

```

### Response 

```typescript
   response.status=201
                    response.body={
                        success: true,
                        data: gunRequest
                    }
```

Add a gun source code 
```typescript
//Add a Gun 

    const  addGun = async({response, request}:{response:any, request:any}) =>{
        // response.body="Post request"
        const body = await request.body()   //body method() which returns a promis we need to use await 
        const gunRequest = body.value
        
         if(!request.hasBody){
            response.status=400
            response.body={
                success: false,
                msg: "No data"
            }

        }else{
          try {
                await client.connect()

                //Adding a gun by uesing the sql command
                    const result = await client.query("INSERT INTO guns(name,description,price VALUES($1,$2,$3))", 
                    gunRequest.name,
                    gunRequest.description,
                    gunRequest.price) //the second parameter here of waht we want to put in thost money signs in sequential order

                //Response
                    response.status=201
                    response.body={
                        success: true,
                        data: gunRequest
                    }
          } catch (error) {
                response.status = 500
                response.body={
                    success: false,
                    msg:error.toString
                }
          }finally{
            // finally this happens after everything is done 
                await client.end()
          }
        }

    }
```


Modify addGun










---





[Reference video](https://www.youtube.com/watch?v=KuaI6mphFNc&t=0s)

https://github.com/bradtraversy/deno-rest-api