-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcatti-index.js
More file actions
101 lines (81 loc) · 2.75 KB
/
Copy pathcatti-index.js
File metadata and controls
101 lines (81 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const Jimp = require('jimp');
exports.handler = async (event) => { //going to return something
const requestObj = getRequestObj(event);
if (requestObj.random === "true") {
requestObj.category = "";
requestObj.text = randomText();
requestObj.rotate = randomNumber(0,360);
requestObj.flip = Math.random() > 0.5 ? "v" : "h";
}
const catUrl = getCat(requestObj);
const base64Str = await manipulateImg("https://cataas.com/cat", requestObj);
return {
headers: {
"Access-Control-Allow-Headers": "Content-Type", // what headers gonna take from request, only allow content type header
"Access-Control-Allow-Origin": "*", // what domain encounter, www or dave.com. Star allows everything.
"Access-Control-Allow-Methods": "OPTIONS, POST, GET"
},
body: JSON.stringify({ base64Str })
};
};
function randomText() {
const rtext = [
"Perfect",
"Pawfect",
"Sweet",
"Lovely"
];
return rtext[Math.floor(Math.random() * rtext.length)];
}
function randomNumber(min, max) {
return Math.floor(Math.random() * max) + min
}
function getRequestObj (event) {
const text = event["queryStringParameters"]["text"];
const rotate = event["queryStringParameters"]["rotate"];
const category = event["queryStringParameters"]["category"];
const flip = event["queryStringParameters"]["flip"]; // v, h, b
const random = event["queryStringParameters"]["random"];
return {
text, rotate, flip, category, random
}
}
function getCat(requestObj) {
if (requestObj.category) {
return `https://cataas.com/cat/${requestObj.category}`
}
return `https://cataas.com/cat`
}
async function manipulateImg(catUrl, requestObj) {
const image = await Jimp.read(catUrl);
let response;
// rotate image
if (requestObj.rotate) {
const rotateDeg = parseInt(requestObj.rotate);
await image.rotate(rotateDeg);
}
// rotate the image. rotate is jimp method
// flip image
if (requestObj.flip === "v") {
await image.flip(false, true);
}
else if (requestObj.flip === "h") {
await image.flip(true, false);
}
else if (requestObj.flip === "b") {
await image.flip(true, true);
}
// same if with the text
if (requestObj.text) {
const font = await Jimp.loadFont(Jimp.FONT_SANS_64_WHITE);
await image.print(font, 50, 50, requestObj.text);
}
// image as base64 string
image.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
if(err) {
return;
}
response = Buffer.from(buffer).toString('base64');
});
return response;
}