Created
          March 14, 2018 20:38 
        
      - 
      
 - 
        
Save saibotsivad/cbd950472e60d7dbe587f4030a4e600f to your computer and use it in GitHub Desktop.  
    example koa based proxy
  
        
  
    
      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
    
  
  
    
  | // imagine that this is the api you want your proxy to interface with | |
| const Koa = require('koa') | |
| const app = new Koa() | |
| app.use(async ctx => { | |
| console.log(ctx.request.method + ' ' + ctx.request.url) | |
| console.log(ctx.request.header['content-type']) | |
| ctx.set('content-type', 'whatevs') | |
| ctx.body = 'yolo' | |
| }) | |
| app.listen(3001) | 
  
    
      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
    
  
  
    
  | // this is the thing that your services would actually use | |
| const got = require('got') | |
| const Koa = require('koa') | |
| const app = new Koa() | |
| const baseUrl = 'http://localhost:3001' | |
| // you'd probably want some sort of authentication for your services | |
| app.use(async ctx => { | |
| console.log(ctx.request.method + ' ' + ctx.request.url) | |
| const incomingContentType = ctx.request.header['content-type'] | |
| const headers = incomingContentType | |
| ? { 'content-type': incomingContentType } | |
| : undefined | |
| // in here somewhere is where you'd manage authenticating to the external api | |
| // pass the url and optional headers through | |
| const stream = got.stream(baseUrl + ctx.request.url, { headers }) | |
| stream.on('response', response => { | |
| // whatever headers come back from the api you can pass along | |
| const contentType = response.headers['content-type'] | |
| ctx.set('content-type', contentType) | |
| }) | |
| ctx.body = stream | |
| }) | |
| app.listen(3000) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment