0.1.2 • Published 4 years ago
@sprdv/hapi-scube v0.1.2
hapi-scube
Hapi plugin to initialize Scube.
Installation
hapi-scube can be installed using npm
or yarn
.
npm install @sprdv/hapi-scube
Usage
This plugin can be registered like any other:
'use strict';
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server();
await server.register({
plugin: require('@sprdv/hapi-scube'),
options: {
accessKey: process.env.AWS_ACCESS_KEY_ID,
secretKey: process.env.AWS_SECRET_ACCESS_KEY
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init();
Options
The following options are available:
- accessKey: an AWS access key associated with an IAM user or role (required).
- secretKey: the secret key associated with the access key (required).
Documentation
This plugin appends a Scube
instance to the server
object:
const { scube } = request.server;
The documentation can then be found in Scube's repository.
Upload a file
Here is a basic route to handle a single file:
server.route({
method: 'POST',
path: '/upload',
options: {
payload: {
parse: true,
output: 'stream',
allow: 'multipart/form-data',
maxBytes: 2 * 1024 * 1024,
multipart: true
},
validate: {
payload: Joi.object({
file: Joi.any().required()
})
}
},
handler: async function(req, h) {
const { file } = req.payload;
const { scube } = req.server;
const name = file.hapi.filename;
const type = file.hapi.headers['content-type'];
const bucket = scube.bucket('my-cool-bucket');
const res = await bucket.newFile(`path/to/folder/${name}`)
.acl('public-read')
.type(type)
.body(file)
.create();
// Save res.location() in your database...
return h.response().code(204);
}
});
Resize and upload a file (using sharp)
Sharp is usually used to convert large images in common formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions:
import sharp from 'sharp';
// Route handler:
const { file } = req.payload;
const { scube } = req.server;
const data = file._data;
const name = file.hapi.filename;
const type = file.hapi.headers['content-type'];
const body = await sharp(data)
.resize(256, 256)
.toBuffer();
const bucket = scube.bucket('my-cool-bucket');
const res = await bucket.newFile(`path/to/folder/${name}`)
.acl('public-read')
.type(type)
.body(body)
.create();
// Save res.location() in your database...