Service for get and post Blueprint 55/84255/3
authorEzhilarasi <ezhrajam@in.ibm.com>
Thu, 4 Apr 2019 15:36:09 +0000 (21:06 +0530)
committerEzhilarasi R <ezhrajam@in.ibm.com>
Fri, 5 Apr 2019 07:10:12 +0000 (07:10 +0000)
Change-Id: Ie99f2ae09e65754e5da5384501f4f8574399da42
Issue-ID: CCSDK-1068
Signed-off-by: Ezhilarasi <ezhrajam@in.ibm.com>
cds-ui/server/package.json
cds-ui/server/src/controllers/blueprint-rest.controller.ts
cds-ui/server/src/datasources/blueprint.datasource.json [new file with mode: 0644]
cds-ui/server/src/datasources/blueprint.datasource.ts [new file with mode: 0644]
cds-ui/server/src/datasources/index.ts
cds-ui/server/src/datasources/rest.datasource.json [moved from cds-ui/server/src/datasources/rest.config.json with 100% similarity]
cds-ui/server/src/datasources/rest.datasource.ts
cds-ui/server/src/services/blueprint.service.ts [new file with mode: 0644]
cds-ui/server/src/services/index.ts [new file with mode: 0644]

index 4d0f946..738a7df 100644 (file)
@@ -1,64 +1,83 @@
 {
-  "name": "cds-ui-server",
-  "version": "1.0.0",
-  "description": "Intermediate layer between UI and backend. Implemented in loopback 4",
-  "keywords": [
-    "loopback-application",
-    "loopback"
-  ],
-  "main": "index.js",
-  "engines": {
-    "node": ">=8.9"
-  },
-  "scripts": {
-    "build:apidocs": "lb-apidocs",
-    "build": "lb-tsc es2017 --outDir dist",
-    "build:watch": "lb-tsc --watch",
-    "clean": "lb-clean dist",
-    "lint": "npm run prettier:check && npm run tslint",
-    "lint:fix": "npm run tslint:fix && npm run prettier:fix",
-    "prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
-    "prettier:check": "npm run prettier:cli -- -l",
-    "prettier:fix": "npm run prettier:cli -- --write",
-    "tslint": "lb-tslint",
-    "tslint:fix": "npm run tslint -- --fix",
-    "pretest": "npm run clean && npm run build",
-    "test": "lb-mocha --allow-console-logs \"dist/test\"",
-    "posttest": "npm run lint",
-    "test:dev": "lb-mocha --allow-console-logs dist/test/**/*.js && npm run posttest",
-    "migrate": "node ./dist/src/migrate",
-    "prestart": "npm run build",
-    "start": "node .",
-    "prepublishOnly": "npm run test"
-  },
-  "repository": {
-    "type": "git"
-  },
-  "author": "",
-  "license": "",
-  "files": [
-    "README.md",
-    "index.js",
-    "index.d.ts",
-    "dist/src",
-    "dist/index*",
-    "src"
-  ],
-  "dependencies": {
-    "@loopback/boot": "^1.0.8",
-    "@loopback/context": "^1.4.0",
-    "@loopback/core": "^1.1.3",
-    "@loopback/openapi-v3": "^1.1.5",
-    "@loopback/repository": "^1.1.1",
-    "@loopback/rest": "^1.5.1",
-    "@loopback/rest-explorer": "^1.1.4",
-    "@loopback/service-proxy": "^1.0.8",
-    "loopback-connector-rest": "^3.4.1"
-  },
-  "devDependencies": {
-    "@loopback/build": "^1.1.0",
-    "@loopback/testlab": "^1.0.3",
-    "@loopback/tslint-config": "^1.0.0",
-    "@types/node": "^10.11.2"
-  }
+    "name": "cds-ui-server",
+    "version": "1.0.0",
+    "description": "Intermediate layer between UI and backend. Implemented in loopback 4",
+    "keywords": [
+        "loopback-application",
+        "loopback"
+    ],
+    "main": "index.js",
+    "engines": {
+        "node": ">=8.9"
+    },
+    "scripts": {
+        "build:apidocs": "lb-apidocs",
+        "build": "lb-tsc es2017 --outDir dist",
+        "build:watch": "lb-tsc --watch",
+        "clean": "lb-clean dist",
+        "lint": "npm run prettier:check && npm run tslint",
+        "lint:fix": "npm run tslint:fix && npm run prettier:fix",
+        "prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
+        "prettier:check": "npm run prettier:cli -- -l",
+        "prettier:fix": "npm run prettier:cli -- --write",
+        "tslint": "lb-tslint",
+        "tslint:fix": "npm run tslint -- --fix",
+        "pretest": "npm run clean && npm run build",
+        "test": "lb-mocha --allow-console-logs \"dist/test\"",
+        "posttest": "npm run lint",
+        "test:dev": "lb-mocha --allow-console-logs dist/test/**/*.js && npm run posttest",
+        "migrate": "node ./dist/src/migrate",
+        "prestart": "npm run build",
+        "start": "node .",
+        "prepublishOnly": "npm run test"
+    },
+    "repository": {
+        "type": "git"
+    },
+    "author": "",
+    "license": "",
+    "files": [
+        "README.md",
+        "index.js",
+        "index.d.ts",
+        "dist/src",
+        "dist/index*",
+        "src"
+    ],
+    "dependencies": {
+        "@loopback/boot": "^1.0.8",
+        "@loopback/context": "^1.4.0",
+        "@loopback/core": "^1.1.3",
+        "@loopback/openapi-v3": "^1.1.5",
+        "@loopback/repository": "^1.1.1",
+        "@loopback/rest": "^1.5.1",
+        "@loopback/rest-explorer": "^1.1.4",
+        "@loopback/service-proxy": "^1.0.8",
+        "@types/form-data": "^2.2.1",
+        "@types/jszip": "^3.1.5",
+        "bluebird": "^3.5.3",
+        "cors": "^2.8.5",
+        "file": "^0.2.2",
+        "file-system": "^2.2.2",
+        "filereader": "^0.10.3",
+        "form-data": "^2.3.3",
+        "formidable": "^1.2.1",
+        "fs": "0.0.1-security",
+        "jszip": "^3.2.1",
+        "loopback-connector-rest": "^3.4.1",
+        "multer": "^1.4.1",
+        "multiparty": "^4.2.1",
+        "nodemon": "^1.18.10"
+    },
+    "devDependencies": {
+        "@loopback/build": "^1.1.0",
+        "@loopback/testlab": "^1.0.3",
+        "@loopback/tslint-config": "^2.0.3",
+        "@types/bluebird": "^3.5.26",
+        "@types/formidable": "^1.0.31",
+        "@types/multer": "^1.3.7",
+        "@types/multiparty": "0.0.32",
+        "@types/node": "^10.11.2",
+        "@types/request": "^2.48.1"
+    }
 }
index 960f09f..ae028af 100644 (file)
@@ -38,123 +38,189 @@ import {
   put,
   del,
   requestBody,
+  Request,
+  Response,
+  RestBindings,
 } from '@loopback/rest';
 import {Blueprint} from '../models';
-import {BlueprintRepository} from '../repositories';
+import { inject } from '@loopback/core';
+import { BlueprintService } from '../services';
+import * as fs from 'fs';
+import * as multiparty from 'multiparty';
+import * as request_lib from 'request';
+
+const REST_BLUEPRINT_CONTROLLER_BASE_URL = process.env.REST_BLUEPRINT_CONTROLLER_BASE_URL || "http://localhost:8080/api/v1";
+const REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER = process.env.REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER || "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==";
 
 export class BlueprintRestController {
   constructor(
-    @repository(BlueprintRepository)
-    public blueprintRepository : BlueprintRepository,
+  //  @repository(BlueprintRepository)
+  //   public blueprintRepository : BlueprintRepository,
+    @inject('services.BlueprintService') 
+    public bpservice: BlueprintService,
   ) {}
 
-  @post('/blueprints', {
+  @get('/blueprints', {
     responses: {
       '200': {
         description: 'Blueprint model instance',
-        content: {'application/json': {schema: {'x-ts-type': Blueprint}}},
+        content: { 'application/json': { schema: { 'x-ts-type': Blueprint } } },
       },
     },
   })
-  async create(@requestBody() blueprint: Blueprint): Promise<Blueprint> {
-    return await this.blueprintRepository.create(blueprint);
-  }
+  async getall() {
+    return await this.bpservice.getAllblueprints(REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER);
 
-  @get('/blueprints/count', {
-    responses: {
-      '200': {
-        description: 'Blueprint model count',
-        content: {'application/json': {schema: CountSchema}},
-      },
-    },
-  })
-  async count(
-    @param.query.object('where', getWhereSchemaFor(Blueprint)) where?: Where,
-  ): Promise<Count> {
-    return await this.blueprintRepository.count(where);
   }
 
-  @get('/blueprints', {
-    responses: {
-      '200': {
-        description: 'Array of Blueprint model instances',
-        content: {
-          'application/json': {
-            schema: {type: 'array', items: {'x-ts-type': Blueprint}},
-          },
+  @post('/create-blueprint')
+  async upload(
+    @requestBody({
+      description: 'multipart/form-data value.',
+      required: true,
+      content: {
+        'multipart/form-data': {
+          // Skip body parsing
+          'x-parser': 'stream',
+          schema: {type: 'object'},
         },
       },
-    },
-  })
-  async find(
-    @param.query.object('filter', getFilterSchemaFor(Blueprint)) filter?: Filter,
-  ): Promise<Blueprint[]> {
-    return await this.blueprintRepository.find(filter);
+    })
+    request: Request,
+    @inject(RestBindings.Http.RESPONSE) response: Response,
+  ): Promise<object> {
+    return new Promise((resolve, reject) => { 
+       this.getFileFromMultiPartForm(request).then(file=>{
+         this.uploadFileToBlueprintController(file, "/blueprint-model/").then(resp=>{
+          response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
+          resolve(JSON.parse(resp.body));
+         }, err=>{
+           reject(err);
+         });
+      }, err=>{
+        reject(err);
+      });
+    });
   }
 
-  @patch('/blueprints', {
-    responses: {
-      '200': {
-        description: 'Blueprint PATCH success count',
-        content: {'application/json': {schema: CountSchema}},
+  @post('/enrich-blueprint')
+  async enrich(
+    @requestBody({
+      description: 'multipart/form-data value.',
+      required: true,
+      content: {
+        'multipart/form-data': {
+          // Skip body parsing
+          'x-parser': 'stream',
+          schema: {type: 'object'},
+        },
       },
-    },
-  })
-  async updateAll(
-    @requestBody() blueprint: Blueprint,
-    @param.query.object('where', getWhereSchemaFor(Blueprint)) where?: Where,
-  ): Promise<Count> {
-    return await this.blueprintRepository.updateAll(blueprint, where);
+    })
+    request: Request,
+    @inject(RestBindings.Http.RESPONSE) response: Response,
+  ): Promise<any> {
+    return new Promise((resolve, reject) => { 
+       this.getFileFromMultiPartForm(request).then(file=>{
+         this.uploadFileToBlueprintController(file, "/blueprint-model/enrich/").then(resp=>{
+           response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
+           response.setHeader("Content-Disposition", resp.headers['content-disposition']);
+           resolve(resp.body);
+         }, err=>{
+           reject(err);
+         });
+      }, err=>{
+        reject(err);
+      });
+    });
   }
 
-  @get('/blueprints/{id}', {
-    responses: {
-      '200': {
-        description: 'Blueprint model instance',
-        content: {'application/json': {schema: {'x-ts-type': Blueprint}}},
-      },
-    },
-  })
-  async findById(@param.path.number('id') id: number): Promise<Blueprint> {
-    return await this.blueprintRepository.findById(id);
+  @get('/download-blueprint/{id}')
+  async download(
+    @param.path.string('id') id: string,
+    @inject(RestBindings.Http.REQUEST) request: Request,
+    @inject(RestBindings.Http.RESPONSE) response: Response,
+  ): Promise<any> {
+    return new Promise((resolve, reject) => { 
+      this.downloadFileFromBlueprintController("/blueprint-model/download/" + id).then(resp=>{
+        response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
+        response.setHeader("Content-Disposition", resp.headers['content-disposition']);
+        resolve(resp.body);
+      }, err=>{
+        reject(err);
+      });
+    });
   }
 
-  @patch('/blueprints/{id}', {
-    responses: {
-      '204': {
-        description: 'Blueprint PATCH success',
-      },
-    },
-  })
-  async updateById(
-    @param.path.number('id') id: number,
-    @requestBody() blueprint: Blueprint,
-  ): Promise<void> {
-    await this.blueprintRepository.updateById(id, blueprint);
+  async getFileFromMultiPartForm(request: Request): Promise<any>{
+    return new Promise((resolve, reject) => {
+      // let options = {
+      //   uploadDir: MULTIPART_FORM_UPLOAD_DIR
+      // }
+      let form = new multiparty.Form();
+      form.parse(request, (err: any, fields: any, files: { [x: string]: any[]; }) => {
+        if (err) reject(err);
+        let file = files['file'][0]; // get the file from the returned files object
+        if(!file){
+          reject('File was not found in form data.');
+        }else{
+          resolve(file);
+        }
+      });
+    })
   }
 
-  @put('/blueprints/{id}', {
-    responses: {
-      '204': {
-        description: 'Blueprint PUT success',
+  async uploadFileToBlueprintController(file: any, uri: string): Promise<any>{
+    let options = {
+      url: REST_BLUEPRINT_CONTROLLER_BASE_URL + uri,
+      headers: {
+        Authorization: REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER,
+        'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
       },
-    },
-  })
-  async replaceById(
-    @param.path.number('id') id: number,
-    @requestBody() blueprint: Blueprint,
-  ): Promise<void> {
-    await this.blueprintRepository.replaceById(id, blueprint);
-  }
+      formData: {
+        file: {
+          value: fs.createReadStream(file.path),
+          options: {
+            filename: 'cba.zip',
+            contentType: 'application/zip'
+          }
+        }
+      }
+    };
 
-  @del('/blueprints/{id}', {
-    responses: {
-      '204': {
-        description: 'Blueprint DELETE success',
-      },
-    },
-  })
-  async deleteById(@param.path.number('id') id: number): Promise<void> {
-    await this.blueprintRepository.deleteById(id);
+    return new Promise((resolve, reject) => {
+      request_lib.post(options, (err: any, resp: any, body: any) => {
+        if (err) {
+          //delete tmp file
+          fs.unlink(file.path, (err: any) => {
+            if (err) {
+              console.error(err);
+              return
+            }
+          })
+          reject(err);
+        }else{
+          resolve(resp);
+        }
+      })
+    })
   }
+
+  async downloadFileFromBlueprintController(uri: string): Promise<any> {
+    let options = {
+      url: REST_BLUEPRINT_CONTROLLER_BASE_URL + uri,
+      headers: {
+        Authorization: REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER,
+      }
+    };
+
+    return new Promise((resolve, reject) => {
+      request_lib.get(options, (err: any, resp: any, body: any) => {
+        if (err) {
+          reject(err);
+        }else{
+          resolve(resp);
+        }
+      })
+    })
 }
+}
\ No newline at end of file
diff --git a/cds-ui/server/src/datasources/blueprint.datasource.json b/cds-ui/server/src/datasources/blueprint.datasource.json
new file mode 100644 (file)
index 0000000..86b1c2c
--- /dev/null
@@ -0,0 +1,22 @@
+{
+    "name": "blueprint",
+    "connector": "rest",
+    "baseURL": "http://localhost:8080/api/v1/",
+    "crud": false,
+    "operations": [{
+        "template": {
+            "method": "GET",
+            "url": "http://localhost:8080/api/v1/blueprint-model/",
+            "headers": {
+                "accepts": "application/json",
+                "content-type": "application/json",
+                "authorization": "{authtoken}"
+            },
+            "responsePath": "$.*"
+        },
+        "functions": {
+            "getAllblueprints": ["authtoken"]
+
+        }
+    }]
+}
\ No newline at end of file
diff --git a/cds-ui/server/src/datasources/blueprint.datasource.ts b/cds-ui/server/src/datasources/blueprint.datasource.ts
new file mode 100644 (file)
index 0000000..0086126
--- /dev/null
@@ -0,0 +1,14 @@
+import {inject} from '@loopback/core';
+import {juggler} from '@loopback/repository';
+import * as config from './blueprint.datasource.json';
+
+export class BlueprintDataSource extends juggler.DataSource {
+  static dataSourceName = 'blueprint';
+
+  constructor(
+    @inject('datasources.config.blueprint', {optional: true})
+    dsConfig: object = config,
+  ) {
+    super(dsConfig);
+  }
+}
index 1726b45..f7a934c 100644 (file)
@@ -21,3 +21,4 @@ limitations under the License.
 
 
 export * from './db.datasource';
+export * from './blueprint.datasource';
index 42cdb80..1b5a44d 100644 (file)
@@ -21,7 +21,7 @@ limitations under the License.
 
 
 import { juggler } from '@loopback/service-proxy';
-import * as config from './rest.config.json';
+import * as config from './rest.datasource.json';
 
 
 export class RestDataSource extends juggler.DataSource {
diff --git a/cds-ui/server/src/services/blueprint.service.ts b/cds-ui/server/src/services/blueprint.service.ts
new file mode 100644 (file)
index 0000000..f482536
--- /dev/null
@@ -0,0 +1,19 @@
+import {getService} from '@loopback/service-proxy';
+import {inject, Provider} from '@loopback/core';
+import {BlueprintDataSource} from '../datasources';
+
+export interface BlueprintService {
+   getAllblueprints(authtoken: string): Promise<any>;
+}
+
+export class BlueprintServiceProvider implements Provider<BlueprintService> {
+  constructor(
+    // blueprint must match the name property in the datasource json file
+    @inject('datasources.blueprint')
+    protected dataSource: BlueprintDataSource = new BlueprintDataSource(),
+  ) {}
+
+  value(): Promise<BlueprintService> {
+    return getService(this.dataSource);
+  }
+}
\ No newline at end of file
diff --git a/cds-ui/server/src/services/index.ts b/cds-ui/server/src/services/index.ts
new file mode 100644 (file)
index 0000000..26b01ed
--- /dev/null
@@ -0,0 +1 @@
+export * from './blueprint.service';