# CareBud Backend Application (Cloud Implementation)

Front-end and back-end are terms used to characterize program interfaces and services relative to the initial user of these interfaces and services. (The "user" may be a human being or a program.) A "front-end" application is one that application users interact with directly. A "back-end" application or program serves indirectly in support of the front-end services, usually by being closer to the required resource or having the capability to communicate with the required resource. The back-end application may interact directly with the front-end or, perhaps more typically, is a program called from an intermediate program that mediates front-end and back-end activities.

The cloud is a term referring to accessing computer, information technology (IT), and software applications through a network connection, often by accessing data centers using wide area networking (WAN) or Internet connectivity.\
Almost all IT resources can live in the cloud: A software program or application, a service, or an entire infrastructure. For example, if a business wanted to build an IT infrastructure, typically it would install the servers, software, and networking resources it needed, but nearly all of those services and resources are now accessible by going to third parties that offer them in the cloud.

In this project I am using Amazon Web Services (AWS) which is a comprehensive, evolving cloud computing platform provided by Amazon. It provides a mix of infrastructure as a service (IaaS), platform as a service (PaaS) and packaged software as a service (SaaS) offerings. Amazon Web Services provides services from dozens of data centers spread across availability and more than 100 services comprise the Amazon Web Services portfolio, including those for compute, databases, infrastructure management, application development and security.

### Cloud Server

Amazon Elastic Compute Cloud (EC2) provides virtual servers or computing instances that can be scalable in terms of computing power and memory, flexible by providing the option to host applications on multiple different platforms, and secure thanks to a tightly coupled multitenant architecture. Amazon EC2 enables the provision of a virtual server, which can incorporate massive amounts of computing power. This is available on a subscription-based utility computing model, and the user is billed only for the resources used.

Amazon Elastic Compute Cloud is a pioneer cloud infrastructure product that allows users to create powerful virtual servers on demand. Amazon EC2 is hosted on the server consolidation/virtualization concept, where the entire computing power of server hardware can be divided into multiple instances and offered to the end-user over the Internet as a computing instance.

![](https://2935399359-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWiNGQeHaFCmpj4-9by%2F-LXvUjkEPD3B1U__tBYf%2F-LXvXSbv8JG-9M2vQQCZ%2FHow-to-launch-an-AWS-EC2-server-and-set-up-Ubuntu-16.04-on-it.jpg?alt=media\&token=6d390d43-6ff0-4a08-815e-5743be40dc70)

Because the computing instances provided are software based, each unique instance is scalable and users can create an entire virtual data centers over the cloud. Amazon EC2-created instances can be accessed by open-source Simple Object Access Protocol (SOAP) application programming interface (API) support, giving developers the liberty to create various types of applications, just as with an on-premises computing infrastructure. The instance provided by EC2, commonly known as a virtual machine, is created using Amazon Virtual Image and is hosted over Xen Hypervisor, a server virtualizing software.

Amazon EC2 virtual servers used in the application as cloud server which running Ubuntu 16.4 operating system, and it can be accessed using SSH connection for example command below.

```bash
ssh -i "fileName.pem" ubuntu@ec2-34-227-106-196.compute-1.amazonaws.com
```

### Cloud Applications

Term Backend comes from (BaaS) Backend as a Service is a cloud computing service model that serves as the middleware that provides developers with ways to connect their Web and mobile applications to cloud services via application programming interfaces (API) and software developers' kits (SDK). BaaS features include cloud storage, push notifications, server code, user and file management, social networking integration, location services, and user management as well as many backend services. These services have their own APIs, allowing them to be integrated into applications with relative ease. With this project there are services used to operate CareBud backend such as (Node.Js, MongoDB Server, Express.Js, mongoose and other related services).

![APPLICATION NETWORK TRANSMISSION DIAGRAM USING REST APIS](https://2935399359-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWiNGQeHaFCmpj4-9by%2F-LXvUjkEPD3B1U__tBYf%2F-LXvZr7JzsRodaTGrVcX%2FArtboard%201historyreport.png?alt=media\&token=6aabd083-dbcc-432a-8be7-9fb4759dfa22)

In the above scenario when user try to communicate with cloud using CareBud application an Api requests such as (GET, POST, PUT and DELETE) will performed during this process which that managed using Node.js is a lean, fast, cross-platform JavaScript runtime environment that is useful for both servers and desktop applications. Express.js, or simply Express, is a web application framework for Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js. In the application when user start to sign Up, on submit a POST request will be created and call an API with SignUp route so data can be stored in the cloud storage (MongoDB) using mongoDb Client.

![REQUEST AND RESPONSE PROCESS BETWEEN MOBILE APPLICATION AND CLOUD BACKEDN](https://2935399359-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWiNGQeHaFCmpj4-9by%2F-LXvUjkEPD3B1U__tBYf%2F-LXv_Hc5aj3omB8j3mNB%2Fimage.png?alt=media\&token=703f00ab-d275-4dba-9a6e-b31fc271155f)

An example code snippet used to call Post Api from CareBud Application SignUp Screen in encrypted format:

## Create New User in CareBud Application

<mark style="color:green;">`POST`</mark> `http://localhost:4000/api/user`

#### Headers

| Name         | Type   | Description        |
| ------------ | ------ | ------------------ |
| Content-Type | string | 'application/json  |
| Accept       | string | 'application/json' |

#### Request Body

| Name       | Type   | Description                                |
| ---------- | ------ | ------------------------------------------ |
| firstName  | string | user first name                            |
| lastName   | string | user last name                             |
| userName   | string | user authentication name                   |
| password   | string | user password                              |
| userType   | string | Doctor/Patient/Relative                    |
| age        | number | user age                                   |
| address    | string | user current address                       |
| userMobile | string | user mobile number used for authentication |
| userEmail  | string | user email address                         |
| location   | number | user GPS Coordinates                       |
| birthDate  | number | user birthdate formatted dd/mm/yyyy        |
| gender     | string | gender male/female                         |
| photo      | string | user photo / support only links for now    |

{% tabs %}
{% tab title="200 " %}

```jsx
{
"statusMessage": "Success",
"message": "Getting user information done!",
"requestType": "post",
"status": "200",
"data": {
"lastName": "/es",
"firstName": "/hn",
"birthDate": "!*4DNTdsu$",
"gender": "@Yqs",
"photo": "",
"_id": "5be3ec87b969822d13d49686",
"userName": "ali",
"password": "PhnDNX",
"userType": "CYyw 5I",
"age": "33",
"address": "oYq15*G=gQtk2NX",
"userMobile": "(/9JMWho ",
"location": [{ 
                "_id": "5be3ec87b969822d13d49687",
                "lng": "548.555*s",
                "lat": "00.555/ws"
                }],
"time_created": "2018-11-08T07:57:59.386Z",
}}
```

{% endtab %}

{% tab title="302 " %}

```jsx
{{statusMessage: "Fails", status: '404', reason: "user already exist!"}}
```

{% endtab %}
{% endtabs %}

The data need to be send and formatted using JSON even when the response received it will be in JSON format. Another snippet show the Server side code for that operation when user POST his data, user account with all details will be created and posted to the MongoDB server.

```javascript
//create new user
router.post(routeDir, function (request, response) {
console.log("Creating User Data", request.body);
User.create(request.body).then(function (success) {
response.status(200).send({statusMessage: "Success", status:
"200", data: success})
console.log("User Created", {statusMessage: "Success",
status: "200", data: success});
}).catch(function (reason) {
response.status(404).send({statusMessage: "Fails", status:
'404', reason: reason})
})});

//THE SERVER SIDE POST OPERATION
```

After creating the account response will be sent to the application with the created encrypted data with status 200 which mean Object created successfully, snippet below show example response:

```jsx
{
"statusMessage": "Success",
"message": "Getting user information done!",
"requestType": "post",
"status": "200",
"data": {
     "lastName": "/es",
     "firstName": "/hn",
     "birthDate": "!*4DNTdsu$",
     "gender": "@Yqs",
     "photo": "",
     "_id": "5be3ec87b969822d13d49686",
     "userName": "ali",
     "password": "PhnDNX",
     "userType": "CYyw 5I",
     "age": "33",
     "address": "oYq15*G=gQtk2NX",
     "userMobile": "(/9JMWho ",
     "location": [{ 
                "_id": "5be3ec87b969822d13d49687",
                "lng": "548.555*s",
                "lat": "00.555/ws"
                }],
     "time_created": "2018-11-08T07:57:59.386Z",
}}
```

Same process happened when the user perform other requests such as PUT, DELETE and GET, below example for adding Doctor D1 to Patient list in the server side.

```jsx
router.put(‘/patient_a ddDoctorDetails’, function (request, response) {
Patient.findByIdAndUpdate({_id: request.body.patient_id}, {$push:
{relatedDoctors_ids: request.body.relatedDoctors_ids}}).then(function () {
Patient.findOne({_id: request.body.patient_id}).then(function
(success) {
   response.status(200).send({
   statusMessage: "Success",
   message: "New patient added successfully",
   requestType: "put",
   status: "200",
   data: success
   })
   }).catch(function (reason) {
      response.status(404).send({
      statusMessage: "Fails",
      status: '404',
      message: "Id " + request.params.id + "is not found",
      reason: reason
   })})
}).catch(function (reason) {
response.status(404).send({
   statusMessage: "Fails",
   status: '404',
   message: "Id " + request.params.id + "is not found",
   reason: reason
}) })

//ADDING DOCTOR D1 TO PATIENT LIST
```

An example code snippet used to get user data using user id:

## Get user data&#x20;

<mark style="color:blue;">`GET`</mark> `http://18.212.177.76/api/user/id`

#### Headers

| Name | Type   | Description      |
| ---- | ------ | ---------------- |
|      | string | application/json |

{% tabs %}
{% tab title="200 " %}

```jsx
"statusMessage": "Success", "message": "Getting user information done!",
"requestType": "get",
"status": "200",
"data": {
"birthDate": "2018-08-11T08:40:27.022Z",
"photo": "https://picjumbo.com/wp-content/uploads/alone-with-his-1080x720.jpg",
"_id": "5b6fe9bbc811ff1a7c14e06e",
"firstName": "Tom",
"lastName": "Zain",
"userName": "tomZain",
"password": "5501781",
"userType": "Patient",
"age": 30,
"address": "Tom Road",
"location": [
{
"_id": "5b6fe9bbc811ff1a7c14e06f",
"lng": 19.555,
"lat": 17.888
}
],
"gender": "male",
"time_created": "2018-08-11T08:40:27.022Z",
"__v": 0
}
```

{% endtab %}

{% tab title="302 " %}

```jsx
{
                statusMessage: "Fails",
                status: '404',
                message: "this user id not found",
                reason: "User Not Exist"
            }
```

{% endtab %}
{% endtabs %}

If the user type is patient then the user will be asked to connect his smart watch so to be able to get user health reports and then at that time we are getting the reports then we encrypt it so to be stored in the cloud using the following APi:

## Create Patient Health Report

<mark style="color:green;">`POST`</mark> `http://18.212.177.76/api/patientHealthStatus`

Create patient health reports

#### Headers

| Name         | Type   | Description      |
| ------------ | ------ | ---------------- |
| Content-Type | string | application/json |

#### Request Body

| Name                        | Type   | Description                                          |
| --------------------------- | ------ | ---------------------------------------------------- |
| user\_id                    | string | user account Id                                      |
| healthStatus\_name          | string | test report name(HeartBeat/Body Temp/BloodPressure)  |
| healthStatus\_description   | string | test report description                              |
| healthStatus\_value         | string | test report value                                    |
| healthStatus\_previousValue | string | test report previous value                           |
| healthStatus\_unit          | string | test report unit                                     |
| effectedTime                | string | test report taken time                               |
| previous\_effectedTime      | string |                                                      |
| bloodPressureReport         | string | if the test is blood pressure require another values |

{% tabs %}
{% tab title="200 This response taken for Blood Pressure report" %}

```jsx
{
"statusMessage": "Success",
"status": "200",
"message":"Report created successfully!",
"data": {
         "user_id":"5b73aa608637cdb228952efb",
         "healthStatus_name" : "Blood Pressure",
         "healthStatus_description" : "blood pressure as a combination of a systolic blood pressure and diastolic blood pressure, and whether the patient was lying down, sitting, or standing when the blood pressure was obtained.",
         "healthStatus_value" : null,
         "healthStatus_previousValue" : null,
         "healthStatus_unit" : "mmHg",
         "effectedTime" : "2018-08-11T08:40:27.022Z",
         "previous_effectedTime" :"2018-08-11T07:30:27.022Z",
         "bloodPressureReport" : [
                  {
                  "systolicBPValue" : 160,
                  "previous_systolicBPValue" : 160,
                  "diastolicBPValue" : 60,
                  "previous_diastolicBPValue" : 60
                  }
]
```

{% endtab %}

{% tab title="302 " %}

```jsx
{statusMessage: "Fails", status: '404', reason: "Required parameter is missing"}
```

{% endtab %}
{% endtabs %}

When we are posting the health report to the backend we encrypt the whole report, the following example show how the report looks like before storing it in the cloud.

```jsx
{
    "patientHealthReportStatus" : [ 
        {
            "_id" : "5c303f0d8e750017ba6f3608",
            "user_id" : "5bf8d7eb8e750017ba6f35ba",
            "healthStatus_name" : "%aozzI%USp /75",
            "healthStatus_description" : "HaozzIHUSp /75_Lm&qC0LUUk yCCTb y H3bduz+3@HMuf 0@@gfsq1ANVTzj'(REUXy*2=GLtez/==ferp0@MUSy)t34_fbj)(2Ohkjr@=6YYdx0HNCdxs2+BFjYs+/MOPjuu*0Udbp*.=2OPdtxDJFNf$'&0WHaozzIHUSp /75_fWx31/QI_pr K",
            "healthStatus_unit" : "SbHr",
            "previous_effectedTime" : "2019-01-03T16:45:29.966Z",
            "bloodPressureReport" : {
                "_id" : "5c303f0d8e750017ba6f3609",
                "systolicBPValue" : "t'6",
                "previous_systolicBPValue" : " ",
                "diastolicBPValue" : "t%",
                "previous_diastolicBPValue" : " +"
            },
            "effectedTime" : "2019-01-05T05:22:21.370Z",
        }, 
        {
            "_id" : "5c303f0d8e750017ba6f360a",
            "user_id" : "5bf8d7eb8e750017ba6f35ba",
            "healthStatus_name" : "%dd)9y8Pbbzt9JRP",
            "healthStatus_description" : "7Vp! @8Qfp).+5_Mii0CFBUgg$yCOWU k()SVUa(#32@bbs!BHDLhf/219d_cj.@HFY_t*DJ=_two)0I",
            "healthStatus_value" : "y+",
            "healthStatus_previousValue" : "y&",
            "healthStatus_unit" : ")",
            "previous_effectedTime" : "2019-01-03T16:45:30.229Z",
            "effectedTime" : "2019-01-05T05:22:21.647Z",
        }, 
        {
            "_id" : "5c303f0d8e750017ba6f360b",
            "user_id" : "5bf8d7eb8e750017ba6f35ba",
            "healthStatus_name" : "+Va!1I'Dfb",
            "healthStatus_description" : "7Vp! @8Qfp)tFEEamt#CEYPXc$3KLFhd+v56bVpz564KKmm#/DDPf!%+JILlqrw%BaMZzz97Rft$%#COOcg.97JcOc x7QEg^ws)EBhsVu!KMHXdwvH5C^xiwEIROY%t(EDLh!r+@UEoqr'+BFlckr5GZ^UwsA8@Ghu! 58Qf",
            "healthStatus_value" : " %",
            "healthStatus_previousValue" : "u&",
            "healthStatus_unit" : "HVa$0UEL_",
            "previous_effectedTime" : "2019-01-03T16:45:30.250Z",
            "effectedTime" : "2019-01-05T05:22:21.664Z",
        }
    ],
    "patient_id" : "5bf8d7eb8e750017ba6f35ba",
}
//patient Health Report Status in encrypted format
```

Get all doctors associated with the patient the response will include patient details and his health status along with all doctors associated with.

## Get Doctors associated with the patient

<mark style="color:blue;">`GET`</mark> `http://18.212.177.76/api/all_doctors_withPatient/5b7851c332254853145f1c38`

#### Headers

| Name         | Type   | Description      |
| ------------ | ------ | ---------------- |
| Content-Type | string | application/json |

{% tabs %}
{% tab title="200 " %}

```javascript
{
"statusMessage": "Success",
"message": "Patient found",
"requestType": "get",
"status": "200",
"patientDetails": {
"relatedDoctors_ids": [
"5b7852c332254853145f1c3a",
"5b7852d632254853145f1c3b",
"5b7852ec32254853145f1c3c"
],
"healthStatus": [
{
"_id": "5b73ab69335380bf380baf00",
"user_id": "5b73aa338637cdb228952ef7",
"healthStatus_name": "Blood Pressure",
"healthStatus_description": "blood pressure as a combination of a systolic blood pressure and diastolic blood pressure, and whether the patient was lying down, sitting, or standing when the blood pressure was obtained.",
"healthStatus_value": null,
"healthStatus_previousValue": null,
"healthStatus_unit": "mmHg",
"effectedTime": "2018-08-11T08:40:27.022Z",
"previous_effectedTime": "2018-08-11T07:30:27.022Z",
"bloodPressureReport": [
{
"_id": "5b73ab69335380bf380baf01",
"systolicBPValue": 160,
"previous_systolicBPValue": 160,
"diastolicBPValue": 60,
"previous_diastolicBPValue": 60
}
],
"__v": 0
},
{
"_id": "5b73ac1b335380bf380baf07",
"user_id": "5b73aa338637cdb228952ef7",
"healthStatus_name": "Heart Rate",
"healthStatus_description": "Represents a person’s heart rate and its relationship to physical activity (resting, or after exercise, etc). The schema can be used either for a single heart rate measurement",
"healthStatus_value": 96.5,
"healthStatus_previousValue": 10.5,
"healthStatus_unit": "beats/min",
"effectedTime": "2018-08-11T08:40:27.022Z",
"previous_effectedTime": "2018-08-11T07:30:27.022Z",
"bloodPressureReport": [],
"__v": 0
}
],
"_id": "5b7851c332254853145f1c38",
"user_id": "5b73aa338637cdb228952ef7",
"__v": 0
},
"relatedDoctorsWithPatient": [
{
"patient_ids": [
"5b77fe8fc0653a0e60a42398"
],
"yearsExperience": 13,
"_id": "5b7852c332254853145f1c3a",
"user_id": "5b784ff232254853145f1c2e",
"__v": 0
},
{
"patient_ids": [
"5b77fe8fc0653a0e60a42398"
],
"yearsExperience": 55,
"_id": "5b7852d632254853145f1c3b",
"user_id": "5b78503d32254853145f1c30",
"__v": 0
},
{
"patient_ids": [
"5b77fe8fc0653a0e60a42398"
],
"yearsExperience": 41,
"_id": "5b7852ec32254853145f1c3c",
"user_id": "5b78504432254853145f1c32",
"__v": 0}]}
```

{% endtab %}
{% endtabs %}

Delete patient account and its related data such as user account and it's all health reports in the Backend

## Delete patient account and its related data

<mark style="color:blue;">`GET`</mark> `http://18.212.177.76/api/patient/5b73ad50335380bf380baf0a`

#### Headers

| Name         | Type   | Description      |
| ------------ | ------ | ---------------- |
| Content-Type | string | application/json |

{% tabs %}
{% tab title="200 " %}

```javascript
{
"statusMessage": "Success",
"message": "Patient deleted successfully",
"requestType": "delete",
"status": "200",
"userResponse": {
"birthDate": "2018-08-11T08:40:27.022Z",
"photo": "https://picjumbo.com/wp-content/uploads/alone-with-his-1080x720.jpg",
"_id": "5b73aa408637cdb228952ef9",
"firstName": "Thala",
"lastName": "Thomes",
"userName": "Thalasss",
"password": "5501781",
"userType": "Patient",
"age": 29,
"address": "Kalimandir Road",
"location": [
{
"_id": "5b73aa408637cdb228952efa",
"lng": 16.555,
"lat": 17.888
}
],
"gender": "male",
"time_created": "2018-08-11T08:40:27.022Z",
"__v": 0
},
"patientResponse": {
"healthStatus": [
{
"_id": "5b73aba1335380bf380baf02",
"user_id": "5b73aa408637cdb228952ef9",
"healthStatus_name": "Blood Pressure",
"healthStatus_description": "blood pressure as a combination of a systolic blood pressure and diastolic blood pressure, and whether the patient was lying down, sitting, or standing when the blood pressure was obtained.",
"healthStatus_value": null,
"healthStatus_previousValue": null,
"healthStatus_unit": "mmHg",
"effectedTime": "2018-08-11T08:40:27.022Z",
"previous_effectedTime": "2018-08-11T07:30:27.022Z",
"bloodPressureReport": [
{
"_id": "5b73aba1335380bf380baf03",
"systolicBPValue": 160,
"previous_systolicBPValue": 160,
"diastolicBPValue": 60,
"previous_diastolicBPValue": 60
}
],
"__v": 0
},
{"_id": "5b73abb1335380bf380baf04",
"user_id": "5b73aa408637cdb228952ef9",
"healthStatus_name": "Body Temperature",
"healthStatus_description": "Represents the body temperature and the location where the measurement was taken.",
"healthStatus_value": 96.5,
"healthStatus_previousValue": 10.5,
"healthStatus_unit": "F",
"effectedTime": "2018-08-11T08:40:27.022Z",
"previous_effectedTime": "2018-08-11T07:30:27.022Z",
"bloodPressureReport": [],
"__v": 0
},
{
"_id": "5b73abc3335380bf380baf06",
"user_id": "5b73aa408637cdb228952ef9",
"healthStatus_name": "Heart Rate",
"healthStatus_description": "Represents a person’s heart rate and its relationship to physical activity (resting, or after exercise, etc). The schema can be used either for a single heart rate measurement",
"healthStatus_value": 96.5,
"healthStatus_previousValue": 10.5,
"healthStatus_unit": "beats/min",
"effectedTime": "2018-08-11T08:40:27.022Z",
"previous_effectedTime": "2018-08-11T07:30:27.022Z",
"bloodPressureReport": [],
"__v": 0
}],
"_id": "5b73ad50335380bf380baf0a",
"user_id": "5b73aa408637cdb228952ef9",
"__v": 0
},
"healthStatusResponse": {
"n": 3,
"ok": 1}}
```

{% endtab %}
{% endtabs %}

Get all patients associated with id: (Doctor) so the doctor can interact with them on first login or on signup, also will be notified.

## Get all patients associated with Doctor

<mark style="color:blue;">`GET`</mark> `http://localhost:4000/api/doctor_getPatient/5b7852c332254853145f1c3a`

#### Headers

| Name         | Type   | Description      |
| ------------ | ------ | ---------------- |
| Content-Type | string | application/json |

{% tabs %}
{% tab title="200 " %}

```jsx
{
"statusMessage": "Success",
"message": "Getting all patient associated with you done!",
"requestType": "get",
"status": "200",
"doctor_id": "5b7852c332254853145f1c3a",
"patient_ids": [
"5b7851c332254853145f1c38",
"5b7862bc88f12b3088289e51",
"5b7862e888f12b3088289e52",
"5b7862f288f12b3088289e53"
]
}
```

{% endtab %}
{% endtabs %}

To review APIs documentation, have a look on the following [link...](https://documenter.getpostman.com/view/3838631/RWTkSeyu#bbda1b33-cd66-42a9-962d-7556ed0e7000)
