Skip to content

Commit 3f4c24c

Browse files
author
Jagveer
committed
Sample app done
1 parent 895daee commit 3f4c24c

File tree

8 files changed

+1397
-2
lines changed

8 files changed

+1397
-2
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
node_modules/*
2+
samples/sample-app/node_modules/*
3+
.vscode

samples/sample-app/.env

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
PRIVATE_KEY =
2+
PUBLIC_KEY =
3+
URL_ENDPOINT =
4+
5+
SERVER_PORT = 3000

samples/sample-app/index.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const path = require('path');
2+
const open = require('open');
3+
const dotenv = require('dotenv').config({path: path.join(__dirname, ".env")});
4+
const server = require('./server/server.js');
5+
6+
7+
const STATIC_PAGE = path.join(__dirname, "client/index.html")
8+
9+
if (dotenv.error) {
10+
throw new Error(dotenv.error);
11+
process.exit(1);
12+
}
13+
14+
const {PRIVATE_KEY, PUBLIC_KEY, URL_ENDPOINT, SERVER_PORT} = dotenv.parsed;
15+
16+
if (!PRIVATE_KEY || !PUBLIC_KEY || !URL_ENDPOINT || !SERVER_PORT) {
17+
throw new Error("Missing values in the '.env' file.")
18+
}
19+
20+
21+
server
22+
.startServer(SERVER_PORT, PUBLIC_KEY, PRIVATE_KEY, URL_ENDPOINT)
23+
.then(() => {
24+
try {
25+
return open(`http://localhost:${SERVER_PORT}`, {wait: true});
26+
} catch (err){
27+
console.error(JSON.stringify(err, undefined, 2))
28+
throw new Error(`Error opening the static page ${STATIC_PAGE}.`)
29+
}
30+
})
31+
.then(() => {
32+
console.log("Exiting app.");
33+
process.exit(0);
34+
})
35+
.catch(err => {
36+
console.log("Error:", JSON.stringify(err, undefined, 2));
37+
process.exit(1);
38+
});
39+
40+
41+

samples/sample-app/package.json

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"name": "imagekit-javascript-sample",
3+
"version": "1.0.0",
4+
"description": "Sample app for javascript SDK of ImageKit",
5+
"main": "index.js",
6+
"license": "MIT",
7+
"dependencies": {
8+
"cors": "^2.8.5",
9+
"crypto": "^1.0.1",
10+
"dotenv": "^8.2.0",
11+
"express": "^4.17.1",
12+
"imagekit": "^3.0.3",
13+
"open": "^7.0.2",
14+
"pug": "^2.0.4",
15+
"uuid": "^3.4.0"
16+
}
17+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
const cors = require('cors');
4+
const ImageKit = require('imagekit');
5+
const uuid = require('uuid');
6+
const fs = require('fs');
7+
const path = require('path');
8+
9+
10+
//const html = fs.readFileSync(path.join(__dirname, "../views/index.html"));
11+
const js = fs.readFileSync(path.join(__dirname, "../../../dist/imagekit.js"));
12+
const pugTemplatePath = path.join(__dirname, "../views/index.pug");
13+
14+
15+
const app = express();
16+
app.use(cors());
17+
app.set('view engine', 'pug');
18+
19+
const startServer = (port = 3000, PUBLIC_KEY, PRIVATE_KEY, URL_ENDPOINT) => {
20+
return new Promise((resolve, reject) => {
21+
try {
22+
const imagekit = new ImageKit({
23+
publicKey: PUBLIC_KEY,
24+
privateKey: PRIVATE_KEY,
25+
urlEndpoint: URL_ENDPOINT
26+
});
27+
28+
29+
router.get("/auth", (req, res) => {
30+
try {
31+
const token = req.query.token || uuid.v4();
32+
const expiration = req.query.expire || parseInt(Date.now()/1000)+ (60 * 10); // Default expiration in 10 mins
33+
34+
const signatureObj = imagekit.getAuthenticationParameters(token, expiration);
35+
36+
// Alternate method for genrating signature
37+
/*
38+
const crypto = require('crypto');
39+
const signatureObj = {
40+
token,
41+
expire: expiration,
42+
signature :crypto.createHmac('sha1', privateAPIKey).update(token+expire).digest('hex')
43+
}
44+
*/
45+
46+
res.status(200).send(signatureObj);
47+
48+
} catch (err) {
49+
console.error("Error while responding to auth request:", JSON.stringify(err, undefined, 2));
50+
res.status(500).send("Internal Server Error");
51+
}
52+
});
53+
54+
router.get("/imagekit.js", (req, res) => {
55+
try {
56+
res.set('Content-Type', 'text/javascript');
57+
res.send(Buffer.from(js));
58+
} catch (err) {
59+
console.error("Error while responding to static page request:", JSON.stringify(err, undefined, 2));
60+
res.status(500).send("Internal Server Error");
61+
}
62+
});
63+
64+
router.get("/", (req, res) => {
65+
try {
66+
res.render(pugTemplatePath, {publicKey: PUBLIC_KEY, urlEndpoint: URL_ENDPOINT, authenticationEndpoint: `http://localhost:3000/auth`});
67+
} catch (err) {
68+
console.error("Error while responding to static page request:", JSON.stringify(err, undefined, 2));
69+
res.status(500).send("Internal Server Error");
70+
}
71+
});
72+
73+
74+
75+
76+
77+
app.use("/",router);
78+
79+
app.listen(port, () => {
80+
console.info(`Auth server running on port ${port}.`);
81+
resolve();
82+
});
83+
} catch (err) {
84+
console.error(JSON.stringify(err, undefined, 2));
85+
reject("Error starting auth server.")
86+
}
87+
88+
});
89+
}
90+
91+
module.exports = {
92+
startServer
93+
}
Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,20 @@
66
<input type="file" id="file1" />
77
<input type="submit" />
88
</form>
9-
<script type="text/javascript" src="../dist/imagekit.js"></script>
9+
<script type="text/javascript" src="/imagekit.js"></script>
1010
<script>
1111
try {
1212
var imagekit = new ImageKit({
1313
publicKey : "your_public_api_key",
1414
urlEndpoint : "https://ik.imagekit.io/your_imagekit_id",
1515
authenticationEndpoint : "http://www.yourserver.com/auth",
16-
});
16+
});
17+
18+
var imagekit = new ImageKit({
19+
publicKey: '81shyFkcqoR/It6sCR1P845UtCY=',
20+
urlEndpoint: 'https://ik.imagekit.io/s11xanjcm/',
21+
authenticationEndpoint: 'http://localhost:3000/auth'
22+
});
1723

1824
function upload(data) {
1925
var file = document.getElementById("file1");

samples/sample-app/views/index.pug

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
html
2+
body
3+
h3 Imagekit Demo
4+
form(action='#' onSubmit='upload(event)')
5+
input(type='file' id='file1')
6+
input(type="submit")
7+
div(id='info')
8+
div(id='status')
9+
10+
div(id='images' style='display: none')
11+
12+
div(id='orig_image')
13+
h4 Original Image
14+
p
15+
img(src="")
16+
div(id='trans_image')
17+
h4 Sample transformation with height: 300, width: 400:
18+
p
19+
img(src="")
20+
21+
script(type='text/javascript' src="/imagekit.js")
22+
script.
23+
try {
24+
var imagekit = new ImageKit({
25+
publicKey: "!{publicKey}",
26+
urlEndpoint: "!{urlEndpoint}",
27+
authenticationEndpoint: "!{authenticationEndpoint}"
28+
});
29+
30+
function upload(e) {
31+
e.preventDefault();
32+
var file = document.getElementById("file1");
33+
var statusEl = document.getElementById("status");
34+
statusEl.innerHTML = "Uploading..."
35+
imagekit.upload({
36+
file : file.files[0],
37+
fileName : "test_image.jpg",
38+
tags : ["test_tag_1"]
39+
}, function(err, result) {
40+
if (err) {
41+
statusEl.innerHTML = "Error uploading image. "+ err.message;
42+
console.log(err)
43+
} else {
44+
statusEl.innerHTML = "File Uploaded";
45+
var sampleTransformations = [{ HEIGHT: 300, WIDTH: 400}];
46+
srcUrl = result.url;
47+
transformedURL = imagekit.url({
48+
src: srcUrl,
49+
transformation : sampleTransformations
50+
});
51+
52+
var orig_img = document.querySelector("#orig_image > p > img");
53+
var trans_img = document.querySelector("#trans_image > p > img");
54+
55+
orig_img.setAttribute("src", srcUrl);
56+
trans_img.setAttribute("src", transformedURL);
57+
58+
var el = document.getElementById('images')
59+
el.setAttribute("style", "");
60+
61+
//- var el = getImageURLElement(imagekit.url({
62+
//- src: srcUrl,
63+
//- transformation : sampleTransformations
64+
//- }));
65+
//- statusEl.appendChild(el);
66+
//- console.log(imagekit.url({
67+
//- src: result.url,
68+
//- transformation : [{ HEIGHT: 300, WIDTH: 400}]
69+
//- }));
70+
}
71+
72+
73+
});
74+
}
75+
76+
function getImageURLElement (url) {
77+
anchorElement = document.createElement('a');
78+
anchorElement.innerHTML = url;
79+
anchorElement.setAttribute("target", "_blank")
80+
anchorElement.setAttribute("href", url);
81+
divElement = document.createElement("div");
82+
divElement.innerHTML = "You can access the image with sample transformation at: "
83+
divElement.appendChild(anchorElement);
84+
return divElement;
85+
}
86+
} catch(ex) {
87+
console.log(ex);
88+
}

0 commit comments

Comments
 (0)