@@ -2,18 +2,21 @@ const express = require('express');
22var cors = require ( 'cors' ) ;
33var app = express ( ) ;
44const atob = require ( 'atob' ) ;
5- // const KEY = require('./key');
5+ const KEY = require ( './key' ) ;
66const Base64 = require ( 'base-64' ) ;
7- const { Sequelize } = require ( 'sequelize' ) ;
8- const KEY = process . env . GITHUB_TOKEN
7+ const { Sequelize, DataTypes } = require ( 'sequelize' ) ;
8+ // const KEY = process.env.GITHUB_TOKEN
99app . use ( cors ( ) )
1010
1111const sequelize = new Sequelize ( 'sqlite::memory:' , {
1212 dialect : 'sqlite' ,
13- storage : 'test .sqlite'
13+ storage : 'db .sqlite'
1414} )
1515
16-
16+ const Item = sequelize . define ( "Item" , {
17+ sha : { type : DataTypes . STRING , allowNull : false } ,
18+ ip : { type : DataTypes . STRING , allowNull : false }
19+ } )
1720
1821const {
1922 default : Axios
@@ -103,12 +106,46 @@ app.get('/add-sha/:sha', (req, res) => {
103106 } )
104107} )
105108
109+ app . get ( '/collect-sha/:sha' , ( req , res ) => {
110+ // const ip = req.headers['x-forwarded-for']
111+ const ip = "176.10.112.40" ;
112+ Item . create ( { sha : req . params . sha , ip : ip } )
113+ const encoded = Base64 . encode ( 1 )
114+ Axios . put ( "https://api.github.com/repos/ujjwal-kr-data/ip-data/contents/" + req . params . sha , {
115+ message : "Added a document" ,
116+ content : encoded
117+ } , {
118+ headers : { 'Authorization' : "token " + KEY }
119+ } ) . then ( result => {
120+ res . json ( { visits : 1 } )
121+ } ) . catch ( e => {
122+ Axios . get ( "https://api.github.com/repos/ujjwal-kr-data/ip-data/contents/" + req . params . sha , {
123+ headers : { 'Authorization' : "token " + KEY }
124+ } ) . then ( result => {
125+ const contentSHA = result . data . sha ;
126+ let visits = Base64 . decode ( result . data . content )
127+ let newVisit = Base64 . encode ( parseInt ( visits ) + 1 )
128+ Axios . put ( "https://api.github.com/repos/ujjwal-kr-data/ip-data/contents/" + req . params . sha , {
129+ message : "UPDATED COUNT" ,
130+ sha : contentSHA ,
131+ content : newVisit
132+ } , { headers : { 'Authorization' : "token " + KEY } } ) . then ( done => {
133+ res . json ( { visits : Base64 . decode ( newVisit ) } )
134+ } )
135+ . catch ( e => console . log ( e ) )
136+ } )
137+ . catch ( e => { console . log ( e ) } )
138+ } )
139+ } )
140+
106141const port = process . env . PORT || 4000 ;
107142app . listen ( port , async ( ) => {
108143 console . log ( `Waiting on port for someone :) ${ port } ` ) ;
109144 try {
110145 await sequelize . authenticate ( ) ;
111146 console . log ( 'Connection has been established successfully.' ) ;
147+ await Item . sync ( )
148+ console . log ( "Item Table Init" )
112149 } catch ( error ) {
113150 console . error ( 'Unable to connect to the database:' , error ) ;
114151 }
0 commit comments