Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GROW-118 Dynamic loan urls and images from Ml recommender #1881

Merged
merged 14 commits into from
Jul 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
195 changes: 110 additions & 85 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"apollo-server-express": "^2.14.4",
"auth0-js": "^9.13.2",
"body-parser": "^1.19.0",
"canvas": "^2.6.1",
"braintree-web-drop-in": "^1.22.1",
"canvas-confetti": "^1.2.0",
"change-case": "^4.1.1",
Expand Down
4 changes: 4 additions & 0 deletions server/dev-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const authRouter = require('./auth-router');
const mockGraphQLRouter = require('./mock-graphql-router');
const sessionRouter = require('./session-router');
const timesyncRouter = require('./timesync-router');
const liveLoanRouter = require('./live-loan-router');
const vueMiddleware = require('./vue-middleware');
const serverConfig = require('../build/webpack.server.conf');
const clientConfig = require('../build/webpack.client.dev.conf');
Expand Down Expand Up @@ -153,6 +154,9 @@ app.use('/ui-routes', serverRoutes);
// Handle time sychronization requests
app.use('/', timesyncRouter());

// dynamic personalized loan routes
app.use('/live-loan', liveLoanRouter(cache));

// install dev/hot middleware
app.use(devMiddleware);
app.use(hotMiddleware);
Expand Down
4 changes: 4 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const authRouter = require('./auth-router');
const mockGraphQLRouter = require('./mock-graphql-router');
const sessionRouter = require('./session-router');
const timesyncRouter = require('./timesync-router');
const liveLoanRouter = require('./live-loan-router');
const vueMiddleware = require('./vue-middleware');
const serverBundle = require('../dist/vue-ssr-server-bundle.json');
const clientManifest = require('../dist/vue-ssr-client-manifest.json');
Expand Down Expand Up @@ -64,6 +65,9 @@ app.use('/ui-routes', serverRoutes);
// Handle time sychronization requests
app.use('/', timesyncRouter());

// dynamic personalized loan routes
app.use('/live-loan', liveLoanRouter(cache));

// Configure session
app.set('trust proxy', 1);
app.use('/', sessionRouter(config.server));
Expand Down
150 changes: 150 additions & 0 deletions server/live-loan-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
const get = require('lodash/get');
const express = require('express');
const argv = require('./util/argv');
const config = require('../config/selectConfig')(argv.config);
const fetch = require('./util/fetch');

const drawLoanCard = require('./util/live-loan/live-loan-draw');

function getLoansFromCache(loginId, cache) {
return new Promise(resolve => {
cache.get(`recommendations-by-login-id-${loginId}`, (error, data) => {
let parsedData = [];
if (error) {
console.error(JSON.stringify({
meta: {},
level: 'error',
message: `MemJS Error Getting recommendations-by-login-id-${loginId}, Error: ${error}`
}));
}
if (data) {
parsedData = JSON.parse(data);
}
resolve(parsedData);
});
});
}

function setLoansToCache(loginId, loans, cache) {
return new Promise((resolve, reject) => {
const expires = 10 * 60; // 10 minutes
cache.set(`recommendations-by-login-id-${loginId}`, JSON.stringify(loans), { expires }, (error, success) => {
if (error) {
console.error(JSON.stringify({
meta: {},
level: 'error',
message: `MemJS Error Setting Cache for recommendations-by-login-id-${loginId}, Error: ${error}`
}));
reject();
}
if (success) {
console.info(JSON.stringify({
meta: {},
level: 'info',
message: `MemJS Success Setting Cache for recommendations-by-login-id-${loginId}, Success: ${success}`
}));
resolve();
}
});
});
}

function fetchRecommendedLoans(loginId, cache) {
return new Promise((resolve, reject) => {
getLoansFromCache(loginId, cache).then(data => {
if (data.length) {
resolve(data);
} else {
const endpoint = config.app.graphqlUri;
const query = `{
ml {
recommendationsByLoginId(
segment: all
loginId: ${loginId}
offset: 0
limit: 4
) {
values {
name
id
borrowerCount
geocode {
country {
name
}
}
use
loanAmount
status
loanFundraisingInfo {
fundedAmount
}
image {
retina: url(customSize: "w960h720")
}
}
}
}
}`;

fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query
}),
})
.then(result => result.json())
.then(result => {
const loanData = get(result, 'data.ml.recommendationsByLoginId.values');
setLoansToCache(loginId, loanData, cache).then(() => {
resolve(loanData);
});
}).catch(err => {
console.error(err);
reject(err);
});
}
}).catch(err => {
console.error(err);
});
});
}

module.exports = function liveLoanRouter(cache) {
const router = express.Router();

// URL Router
router.use('/u/:userId/url/:offset', async (req, res) => {
const { userId, offset } = req.params;
try {
const loanData = await fetchRecommendedLoans(userId, cache);
const offsetLoanId = loanData[offset - 1].id;
res.redirect(302, `/lend/${offsetLoanId}`);
ryan-ludwig marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
console.error(err);
res.redirect(302, '/lend-by-category/');
}
});

// IMG Router
router.use('/u/:userId/img/:offset', async (req, res) => {
const { userId, offset } = req.params;
try {
const loanData = await fetchRecommendedLoans(userId, cache);
const loanCardImgBuffer = await drawLoanCard(loanData[offset - 1]);
ryan-ludwig marked this conversation as resolved.
Show resolved Hide resolved
res.contentType('image/jpeg');
res.send(loanCardImgBuffer);
} catch (err) {
console.error(err);
res.sendStatus(500);
}
});

// 404 any /live-loan/* routes that don't match above
router.use((req, res) => {
res.sendStatus(404);
});

return router;
};
78 changes: 78 additions & 0 deletions server/util/live-loan/canvas-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
module.exports = {
/**
* Returns a single line of text. Adds ellipsis if text overflows the desired canvas width
* @param {CanvasRenderingContext2D} ctx
* @param {String} str The text to draw
* @param {Number} maxWidth The width in pixels of the line
*/
ellipsisLine(ctx, str, maxWidth) {
let { width } = ctx.measureText(str);
const ellipsis = '…';
const ellipsisWidth = ctx.measureText(ellipsis).width;
if (width <= maxWidth || width <= ellipsisWidth) {
return str;
}
let len = str.length;
while (width >= maxWidth - ellipsisWidth && len-- > 0) {
str = str.substring(0, len);
width = ctx.measureText(str).width;
}
return str + ellipsis;
},

/**
* Draws a rounded rectangle to the current state of the canvas.
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} [radius = 0] The corner radius;
*/
roundRect(ctx, x, y, w, h, r) {
if (w < 2 * r) r = w / 2;
if (h < 2 * r) r = h / 2;
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
},

/**
* Draws multiple lines of text to the current state of the canvas.
* Adds an ellispsis if the text overflows.
* @param {CanvasRenderingContext2D} ctx
* @param {String} text The st
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} maxWidth The width of the rectangle
* @param {Number} maxLines The max number of lines in the paragraph
* @param {Number} lineHeight The lineHeight in px of the text
*/
wrapText(ctx, text, x, y, maxWidth, maxLines, lineHeight) {
const words = text.split(' ');
let line = '';
let numLines = 1;

for (let n = 0; n < words.length; n++) {
const testLine = `${line + words[n]} `;
const metrics = ctx.measureText(testLine);
const testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
if (numLines < maxLines) {
ctx.fillText(line, x, y);
line = `${words[n]} `;
y += lineHeight;
numLines += 1;
} else if (numLines === maxLines) {
line = module.exports.ellipsisLine(ctx, testLine, maxWidth);
}
} else {
line = testLine;
}
}
ctx.fillText(line, x, y);
}
};
Loading