Skip to content

Instantly share code, notes, and snippets.

@SamuelColeman
Last active November 13, 2019 19:51
Show Gist options
  • Select an option

  • Save SamuelColeman/c15f9c7fe1f198054f58fb8b382101fb to your computer and use it in GitHub Desktop.

Select an option

Save SamuelColeman/c15f9c7fe1f198054f58fb8b382101fb to your computer and use it in GitHub Desktop.
Mod 4 pre work deliverable
const http = require("http");
const url = require('url');
const server = http.createServer();

server.listen(3000, () => {
  console.log('The HTTP server is listening at Port 3000.');
});

// server.on('request', (request, response) => {
//   response.writeHead(200, { 'Content-Type': 'text/plain' });
//   response.write('Hello World\n');
//   response.end();
// });

let messages = [
  { 'id': 1, 'user': 'brittany storoz', 'message': 'hi there!' },
  { 'id': 2, 'user': 'bob loblaw', 'message': 'check out my law blog' },
  { 'id': 3, 'user': 'lorem ipsum', 'message': 'dolor set amet' }
];

server.on('request', (request, response) => {
  if (request.method === 'GET') {
    getAllMessages(response);
  }

  else if (request.method === 'POST') {
    let newMessage = { 'id': new Date() };

    request.on('data', (data) => {
      newMessage = Object.assign(newMessage, JSON.parse(data));
    });

    request.on('end', () => {
      addMessage(newMessage, response);
    });
  }
});

const getAllMessages = (response) => {
	response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.write(JSON.stringify(messages));
  response.end();
};

const addMessage = (newMsg, response) => {
	response.writeHead(201, { 'Content-Type': 'text/plain' });
	response.write(JSON.stringify({ 'id': newMsg.id, 'user': 'alex trebek', 'message': 'answer in the form of a question' }));
  response.end();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment