Skip to content

Commit

Permalink
feat: added post endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigomata committed May 17, 2019
1 parent 00c4430 commit ed832d7
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ NodeJS Logging stream example

## Usage
1. Run the server with `npm run start`
2. Try sending a POST request to `http://localhost:20019/logging` (Replace *logging* with any filename).
2. Try sending a POST request to `http://localhost:8080/logging` (Replace *logging* with any filename).
35 changes: 35 additions & 0 deletions src/api/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// :: Using streams to avoid loading the entire file in order to write to it.
// :: This will allow scalability, and prevent large memory reads

import { createReadStream, createWriteStream } from 'fs'
// :: This library helps wrapping a generator into a readable stream to be piped
// :: https://www.npmjs.com/package/async-stream-generator
const streamify = require("async-stream-generator");

// :: Use a generator to wait to the read stream to finish, adding chunks to later parse them
async function* addChunk(chunks: any, body: any) {
let data = ''
for await (const chunk of chunks) {
data += chunk.toString()
}
// :: Small validation in case the file is empty
const modifiedChunk = data.length ? JSON.parse(data) : []
// :: Add data as requested
modifiedChunk.push([(new Date).getTime(), body])
yield JSON.stringify(modifiedChunk)
}

// :: Having this functionality separated, allows the code to be more readable and maintanable
export const saveData = (request: any, response: any) => {
// :: The name of the file to create
const file = `${request.params.target}.log`
// :: The read stream is created with a+ to create log files in case they do not exist
const readStream = createReadStream(file, { flags: 'a+' })
// :: Overriden default write flag, to avoid the file to be truncated
const writeStream = createWriteStream(file, { flags: 'r+' })
// :: Pipe the streams
streamify(addChunk(readStream, request.body)).pipe(writeStream)

// :: Send the response as we are not waiting for the log to finish
response.status(200).send('Log updated')
}
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from 'express'
import { saveData } from './api/post'

const server = express()
server.use(express.json());

// :: Endpoint that parses requests
server.post('/:target', saveData)

const port = process.env.PORT || 8080
server.listen(port, () => console.info(`Server started at http://localhost:${port}`))

0 comments on commit ed832d7

Please sign in to comment.