From 877287574b6694869d9dbe1262486d28d137f687 Mon Sep 17 00:00:00 2001 From: rubenwardy Date: Thu, 19 Jan 2017 13:18:21 +0000 Subject: [PATCH] Add FarmerAPI class to Worker --- package.json | 1 + service/farmerapi.js | 31 +++++++++++++++++++++++ service/index.js | 12 +++++++++ webapp/controllers/workerapi.js | 44 +++++++++++++++++++-------------- 4 files changed, 69 insertions(+), 19 deletions(-) create mode 100644 service/farmerapi.js diff --git a/package.json b/package.json index 8f84af9..074fe6e 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "body-parser": "^1.15.2", "express": "^4.14.0", "express-liquid": "^0.2.6", + "request": "^2.79.0", "sequelize": "^3.28.0", "sqlite3": "^3.1.8" } diff --git a/service/farmerapi.js b/service/farmerapi.js new file mode 100644 index 0000000..cebded1 --- /dev/null +++ b/service/farmerapi.js @@ -0,0 +1,31 @@ +"use strict" + +var request = require("request") +var API_URL = "http://localhost:8080" + +class FarmerAPI { + getWork() { + return new Promise(function(resolve, reject) { + request.get({ + url: API_URL + '/workers/get-work', + qs: { + token: "foobar" + }, + json: true, + // auth: { + // username: me.username, + // password: me.password, + // sendImmediately: true + // } + }, function (error, response, body) { + if (!error && response.statusCode == 200) { + resolve(body.work) + } else { + reject(error) + } + }) + }) + } +} + +module.exports = FarmerAPI diff --git a/service/index.js b/service/index.js index eebe0fb..e28cb19 100644 --- a/service/index.js +++ b/service/index.js @@ -1 +1,13 @@ "use strict" + +require("process").chdir(__dirname) + +const FarmerAPI = require("./farmerapi") +const api = new FarmerAPI() + +api.getWork().then(function(r) { + console.log("r: ") + console.log(r); +}).catch(function(e) { + console.log("e" + e) +}) diff --git a/webapp/controllers/workerapi.js b/webapp/controllers/workerapi.js index 0d8f749..42770af 100644 --- a/webapp/controllers/workerapi.js +++ b/webapp/controllers/workerapi.js @@ -11,25 +11,31 @@ router.get("/get-work", function(req, res) { token: worker_token } }).then(function(worker) { - db.Work.findAll({ - limit: 1, - where: { - workerId: null - } - }).then(function(jobs) { - if (jobs && jobs.length == 1) { - var job = jobs[0] - job.workerId = worker.id - job.save() - res.send({ - author: job.author, - basename: job.basename, - type: job.work_type - }) - } else { - res.send({}) - } - }) + if (worker) { + db.Work.findAll({ + limit: 1, + where: { + workerId: null + } + }).then(function(jobs) { + if (jobs && jobs.length == 1) { + var job = jobs[0] + job.workerId = worker.id + job.save() + res.send({ + work: { + author: job.author, + basename: job.basename, + type: job.work_type + } + }) + } else { + res.send({}) + } + }) + } else { + res.status(401).status("Unauthorized") + } }) })