Last active
May 12, 2016 14:24
-
-
Save DeadAlready/fc353d804a1d1767d8cc01bd05c7a8fd to your computer and use it in GitHub Desktop.
NPM registry piper
This file contains 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'; | |
const express = require('express'); | |
const request = require('request'); | |
const morgan = require('morgan'); | |
let app = express(); | |
app.use(morgan('short')); | |
function maskVersion(version){ | |
// Replace the url so downloading a package also hits our server | |
version.dist.tarball = version.dist.tarball | |
.replace('https://registry.npmjs.org', 'http://localhost:3000'); | |
return version; | |
} | |
function mask(obj) { | |
Object.keys(obj.versions).forEach(key => { | |
obj.versions[key] = maskVersion(obj.versions[key], name); | |
}); | |
return obj; | |
} | |
function getMetadata(name) { | |
return new Promise((resolve, reject) => { | |
request(`https://registry.npmjs.org/${name}`, function (err, response, body) { | |
//Error so reject | |
if(err) { reject(err); return; } | |
let data = JSON.parse(body); | |
resolve(mask(data)); | |
}); | |
}); | |
} | |
//Morgan only logs the request once it is complete | |
//this logs the start of the request | |
app.get('*', function (req, res, next) { | |
console.log(req.path); | |
next(); | |
}); | |
app.get('/:name', function (req, res) { | |
getMetadata(req.params.name).then(data => res.json(data)); | |
}); | |
app.get('*', function (req, res) { | |
request | |
.get(`https://registry.npmjs.org${req.path}`) | |
.pipe(res); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment