Last active
November 16, 2016 16:14
-
-
Save jschr/f84a71727beef02eb7d6e49fbc8ceafe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
require('dotenv').load() | |
const Promise = require('bluebird') | |
const AppCompiler = require('@spin-io/sdk-app-compiler') | |
const tar = require('tar-stream') | |
const gzip = require('zlib').Gzip | |
const request = require('request') | |
function makeResponse(statusCode, body) { | |
if (statusCode < 400) { | |
console.info('Success: ', body) | |
} else { | |
console.error('Error: ', body) | |
} | |
return { | |
statusCode, | |
body: JSON.stringify(body), | |
headers: { | |
'Access-Control-Allow-Methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT', | |
'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token', | |
'Access-Control-Allow-Origin': '*' | |
} | |
} | |
} | |
module.exports.handler = (event, context, cb) => { | |
const params = typeof event.body === 'string' | |
? JSON.parse(event.body) | |
: event.body | |
console.log('params: ', params) | |
const compiler = new AppCompiler({ | |
name: params.name, | |
props: params.props, | |
source: params.source | |
}) | |
const endpoint = params.endpoint | |
compiler.compile() | |
.then((compilation) => { | |
const stats = compilation.stats | |
const files = compilation.files | |
console.info('stats: ', stats) | |
console.info('files: ', Object.keys(files)) | |
return files | |
}) | |
.then((files) => { | |
const pack = tar.pack() | |
let size = 0 | |
let count = 0 | |
pack.entry({ name: '/dist', type: 'directory' }) | |
Object.keys(files).forEach((name) => { | |
const file = files[name] | |
count += 1 | |
size += Buffer.byteLength(file) | |
pack.entry({ name }, file) | |
}) | |
const url = `https://surge.surge.sh/${endpoint}.spin-app.io` | |
const token = '[token]' | |
const headers = { | |
version: '0.18.0', | |
'file-count': count, | |
'project-size': size | |
} | |
pack.finalize() | |
return new Promise((resolve, reject) => { | |
const upload = request.put(url, headers) | |
.auth('token', token) | |
.on('error', reject) | |
.on('data', d => console.log('data', d)) | |
.on('response', res => console.log('res', res)) | |
.on('end', resolve) | |
pack | |
.pipe(gzip()) | |
.pipe(upload) | |
}) | |
}) | |
.then(() => `http://${endpoint}.spin-app.io`) | |
.then(url => cb(null, makeResponse(200, { url }))) | |
.catch(err => cb(null, makeResponse(500, { message: err.message }))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment