-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.ts
More file actions
204 lines (166 loc) · 5.49 KB
/
Copy pathhandler.ts
File metadata and controls
204 lines (166 loc) · 5.49 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Load requirements
import { APIGatewayEvent, Context, Callback } from 'aws-lambda';
import * as request from 'request-promise-native';
import * as Ajv from 'ajv';
import * as fileType from 'file-type';
import * as Sharp from 'sharp';
import * as Smartcrop from 'smartcrop-sharp';
import { Schema } from './options/options.schema';
import { Mimes } from './options/options.mimes';
// Image handler
export function images(event: APIGatewayEvent, context: Context, callback: Callback) {
// Setup request validator
const ajv = new Ajv({coerceTypes: true, useDefaults: true});
const validate = ajv.compile(Schema);
// Validate the incoming request params
if ( validate(event.queryStringParameters) === false ) {
return callback(null, {
statusCode: 400,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({message: 'Input validation failed: ' + ajv.errorsText(validate.errors).replace('data.', '')})
});
}
// Build S3 image url
const url = `${process.env.S3_URL}/${event.pathParameters.store}/${event.pathParameters.image}`;
// Get the image
request({url, encoding: null})
// Start the manipulation
.then(async (image: Buffer) => {
// Variables
let query = event.queryStringParameters;
// Skip without anything to do
if ( query === null || Object.keys(query).length <= 0 ) {
return Promise.resolve(image);
}
// Get the initial file type data
let metadata = fileType(image);
// Check mime type is something we can work with
if ( ! Mimes.includes(metadata.mime) ) {
throw new Error(`Invalid file type provided (${metadata.mime})`);
}
// Start an instance of sharp for our image
let sharp = Sharp(image);
// Smartcrop
if ( query.fit === 'smart' ) {
// Find the best crop for this image
let result = await Smartcrop.crop(image, {
width: ( query.width || undefined ),
height: ( query.height || undefined )
});
// Perform crop
sharp.extract({
left: result.topCrop.x,
top: result.topCrop.y,
width: result.topCrop.width,
height: result.topCrop.width
});
// Reset fit to default
query.fit = 'cover';
}
// Trim
if ( query.trim ) {
sharp.trim(query.trim);
}
// Rotate
if ( query.rotate ) {
sharp.rotate(query.rotate, {background: ( query.background || undefined )});
// Flatten the alpha layer to allow background color to show through
if ( query.background !== undefined && query.background !== 'transparent' ) {
sharp.flatten({ background: query.background});
}
}
// Crop
if ( query.width && query.height && query.left && query.top ) {
sharp.extract({left: query.left, top: query.top, width: query.width, height: query.height});
// Resize
} else if ( query.width && query.height ) {
sharp.resize(query.width, query.height, {fit: query.fit});
} else if ( query.width ) {
sharp.resize(query.width, query.width, {fit: query.fit});
} else if ( query.height ) {
sharp.resize(query.height, query.height, {fit: query.fit});
}
// Flatten alpha layers or add background
if ( query.flatten === 1 || ( query.background !== undefined && query.background !== 'transparent' ) ) {
sharp.flatten({background: ( query.background || undefined )});
}
// Flip/flop
if ( query.flip === 'xy' || query.flip === 'yx' ) {
sharp.flip().flop();
} else if ( query.flip === 'y' ) {
sharp.flip();
} else if ( query.flip === 'x' ) {
sharp.flop();
}
// Sharpen
if ( query.sharpen ) {
sharp.sharpen();
}
// Blur
if ( query.blur ) {
sharp.blur(query.blur);
}
// Gamma
if ( query.gamma ) {
sharp.gamma(query.gamma);
}
// Tint
if ( query.tint ) {
sharp.tint(query.tint);
}
// Grayscale/greyscale
if ( query.grayscale || query.greyscale ) {
sharp.greyscale(true);
}
// Negative
if ( query.negative ) {
sharp.negate(true);
}
// Progressive JPEG
if ( query.progressive && metadata.mime === 'image/jpeg' ) {
sharp.jpeg({progressive: true});
// Progressive PNG
} else if ( query.progressive && metadata.mime === 'image/png' ) {
sharp.png({progressive: true});
}
// Render the new image
return sharp.toBuffer();
})
// Send back to user
.then((image: Buffer) => {
// Get final file type data
let metadata = fileType(image);
// Convert and return the image to the user
return callback(null, {
statusCode: 200,
headers: {
'Content-Type': metadata.mime
},
body: image.toString('base64'),
isBase64Encoded: true
});
})
// Error handler
.catch((err) => {
// Request error, 404
if ( err.statusCode ) {
return callback(null, {
statusCode: 404,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({message: 'Image not found'})
});
}
// General error
return callback(null, {
statusCode: 500,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({message: err.message})
});
});
};