File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,8 @@ npm i upring-kv --save
1616
1717## Usage
1818
19+ See [ ./example.js] ( ./example.js ) for exposing upring-kv over HTTP.
20+
1921## API
2022
2123 * <a href =" #constructor " ><code >UpRingKV</code ></a >
Original file line number Diff line number Diff line change 1+ 'use strict'
2+
3+ const UpRingKV = require ( '.' )
4+ const http = require ( 'http' )
5+
6+ const db = UpRingKV ( {
7+ base : process . argv . slice ( 2 ) ,
8+ hashring : {
9+ joinTimeout : 200
10+ }
11+ } )
12+
13+ db . upring . on ( 'up' , function ( ) {
14+ console . log ( 'to start a new peer, copy and paste the following in a new terminal:' )
15+ console . log ( 'node example' , this . whoami ( ) )
16+
17+ const server = http . createServer ( function ( req , res ) {
18+ switch ( req . method ) {
19+ case 'PUT' :
20+ case 'POST' :
21+ handlePost ( req , res )
22+ break
23+ case 'GET' :
24+ handleGet ( req , res )
25+ break
26+ default :
27+ res . statusCode = 404
28+ res . end ( )
29+ }
30+ } )
31+
32+ server . listen ( 0 , function ( err ) {
33+ if ( err ) {
34+ throw err
35+ }
36+
37+ console . log ( 'server listening on' , server . address ( ) )
38+ } )
39+
40+ function handleGet ( req , res ) {
41+ db . get ( req . url , function ( err , data ) {
42+ if ( err ) {
43+ res . statusCode = 500
44+ res . end ( err . message )
45+ return
46+ }
47+
48+ if ( ! data ) {
49+ res . statusCode = 404
50+ res . end ( )
51+ return
52+ }
53+
54+ res . setHeader ( 'Content-Type' , data . contentType )
55+ res . end ( data . value )
56+ } )
57+ }
58+
59+ function handlePost ( req , res ) {
60+ var str = ''
61+
62+ req . on ( 'data' , function ( chunk ) {
63+ str += chunk . toString ( )
64+ } )
65+
66+ req . on ( 'error' , function ( err ) {
67+ res . statusCode = 500
68+ res . end ( err . message )
69+ } )
70+
71+ req . on ( 'end' , function ( ) {
72+ db . put ( req . url , {
73+ contentType : req . headers [ 'content-type' ] ,
74+ value : str
75+ } , function ( err ) {
76+ if ( err ) {
77+ res . statusCode = 500
78+ res . end ( err . message )
79+ } else {
80+ res . statusCode = 200
81+ res . end ( )
82+ }
83+ } )
84+ } )
85+ }
86+ } )
You can’t perform that action at this time.
0 commit comments