Skip to content

Commit

Permalink
Add /works/{id}/thumbnail route
Browse files Browse the repository at this point in the history
  • Loading branch information
mbklein committed Aug 24, 2022
1 parent 87aba31 commit ad921c4
Show file tree
Hide file tree
Showing 9 changed files with 374 additions and 18 deletions.
196 changes: 190 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@aws-sdk/signature-v4": "^3.130.0",
"axios": ">=0.21.1",
"base64-js": "^1.5.1",
"jsonwebtoken": "^8.5.1",
"lz-string": "^1.4.4"
},
"scripts": {
Expand Down
13 changes: 12 additions & 1 deletion src/aws/environment.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
const jwt = require("jsonwebtoken");

function apiToken() {
const token = {
displayName: ["Digital Collection API v2"],
iat: Math.floor(Number(new Date()) / 1000),
};

return jwt.sign(token, process.env.API_TOKEN_SECRET);
}

function elasticsearchEndpoint() {
return process.env.ELASTICSEARCH_ENDPOINT;
}
Expand All @@ -12,4 +23,4 @@ function region() {
return process.env.AWS_REGION || "us-east-1";
}

module.exports = { elasticsearchEndpoint, prefix, region };
module.exports = { apiToken, elasticsearchEndpoint, prefix, region };
58 changes: 58 additions & 0 deletions src/handlers/get-work-thumbnail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const { apiToken } = require("../aws/environment");
const axios = require("axios").default;
const middleware = require("./middleware");
const { getWork } = require("../api/opensearch");
const opensearchResponse = require("../api/response/opensearch");

function getAxiosResponse(url, config) {
return new Promise((resolve) => {
axios
.get(url, config)
.then((response) => resolve(response))
.catch((error) => resolve(error.response));
});
}

/**
* A simple function to proxy a Work's thumbnail from the IIIF server
*/
exports.handler = async (event) => {
event = middleware(event);
const id = event.pathParameters.id;
const esResponse = await getWork(id);
if (esResponse.statusCode != 200) {
return opensearchResponse.transform(esResponse);
}

const body = JSON.parse(esResponse.body);
const thumbnail = body?._source?.thumbnail;

if (thumbnail === undefined) {
return {
statusCode: 404,
body: "Not Found",
};
}

const { status, headers, data } = await getAxiosResponse(thumbnail, {
headers: { Authorization: `Bearer ${apiToken()}` },
responseType: "arraybuffer",
});

if (status != 200) {
return {
statusCode: status,
body: data.toString(),
headers: headers,
};
}

return {
statusCode: status,
isBase64Encoded: true,
body: data.toString("base64"),
headers: {
"content-type": headers["content-type"],
},
};
};
Loading

0 comments on commit ad921c4

Please sign in to comment.