-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.js
More file actions
180 lines (163 loc) · 4.91 KB
/
Copy pathindex.js
File metadata and controls
180 lines (163 loc) · 4.91 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
'use strict';
const aws = require('aws-sdk');
const doc = new aws.DynamoDB.DocumentClient();
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
// Map of routes to functions
var routes = {
'/': index,
'/create': create
};
// Handler provides routing
exports.handler = function(event, context, callback) {
console.log(event);
if (routes[event.path]) {
return routes[event.path](event, context, callback);
} else {
redirect(event, context, callback);
}
};
// Serve the index page
function index(event, context, callback) {
// Determine base path on whether the API Gateway stage is in the path or not
let base_path = '/';
if (event.requestContext.path.startsWith('/' + event.requestContext.stage)) {
base_path = '/' + event.requestContext.stage + '/';
}
let filePath = path.join(process.env.LAMBDA_TASK_ROOT, 'public/index.html');
// Read the file, fill in base_path and serve, or 404 on error
fs.readFile(filePath, function(err, data) {
if (err) {
return done(404, '{"message":"Not Found"}', 'application/json', callback);
}
let content = data.toString().replace(/{{base_path}}/g, base_path);
return done(200, content, 'text/html', callback);
});
}
// Create a new teeny url
function create(event, context, callback) {
var json;
if (!event.body) {
return done(400, '{"error": "Missing body"}', 'application/json', callback);
}
try {
json = JSON.parse(event.body);
} catch (e) {
return done(400, '{"error": "Invalid JSON body"}', 'application/json', callback);
}
shortSave(json.longUrl, function(err, data) {
if (err) {
return done(500, '{"error": "Internal Server Error"}', 'application/json', callback);
} else {
return done(200, data.toString(), 'application/json', callback);
}
});
}
// Try to load the long url and redirect, otherwise 404
function redirect(event, context, callback) {
var shortKey = getShortKey(event.path);
loadLong(shortKey, function(err, longUrl) {
if (err) {
return done(404, '{"status": "Not Found"}', 'application/json', callback);
} else {
console.log('Redirecting short key ' + shortKey + ' to ' + longUrl);
return callback(null, {
statusCode: 302,
body: '',
headers: {
'Location': longUrl
}
});
}
});
}
// shortKey is the first url segment e.g. 'abc' in '/abc' or '/abc/def'
function getShortKey(path) {
var shortKey = path.substring(1);
var slashIndex = shortKey.indexOf('/');
if (slashIndex > 0) {
shortKey = shortKey.substring(0, slashIndex);
}
return shortKey;
}
// Generate the short path for the given url and store it in the database
function shortSave(longUrl, callback, keyHash = '', length = 2) {
// hash the url if necessary
if (!keyHash) {
keyHash = hash(longUrl);
}
// calculate the shortKey based on the received length
var shortKey = keyHash.substring(0, length);
// Store the mapping of shortKey to longUrl, only if the shortKey is new
// or this data is already stored
var params = {
TableName: process.env.URL_TABLE,
Item: {
id: shortKey,
longUrl: longUrl
},
ConditionExpression: 'attribute_not_exists(id) or longUrl = :url',
ExpressionAttributeValues: {
':url': longUrl
}
};
doc.put(params, function(err, data) {
if (err) {
if (err.code === 'ConditionalCheckFailedException') {
// Key collision, try again with a longer shortKey
if (length < keyHash.length) {
shortSave(longUrl, callback, keyHash, length + 1);
} else {
console.error('Key collision, but cannot make key longer: ', err);
return callback(err);
}
} else {
console.error('DyanmoDB error on save: ', err);
return callback(err);
}
} else {
// Key saved: return success
return callback(null, JSON.stringify({shortKey: shortKey}));
}
});
}
// Sha256 the given url
function hash(url) {
var sha = crypto.createHash('sha256');
sha.update(url);
return sha.digest('base64');
}
// Load the long url from the database
function loadLong(shortKey, callback) {
var params = {
TableName: process.env.URL_TABLE,
Key: {
id: shortKey
}
};
doc.get(params, function(err, data) {
if (err) {
console.log('DynamoDB error on load: ', err);
return callback(err);
} else if (!data.Item) {
var msg = 'No data for shortKey: ' + shortKey;
console.log(msg);
return callback(new Error(msg));
} else {
console.log('Got data: ', data);
return callback(null, data.Item.longUrl);
}
});
}
// We're done with this lambda, return to the client with given parameters
function done(statusCode, body, contentType, callback, isBase64Encoded = false) {
callback(null, {
statusCode: statusCode,
isBase64Encoded: isBase64Encoded,
body: body,
headers: {
'Content-Type': contentType
}
});
}