Skip to content

Commit

Permalink
Merge pull request reactjs#96 from zpao/ids-for-data
Browse files Browse the repository at this point in the history
Add ids to data server-side so that keys can be used client-side
  • Loading branch information
zpao committed Nov 12, 2015
2 parents a45fe12 + 0e7f1b2 commit aa6e9a8
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 11 deletions.
2 changes: 2 additions & 0 deletions comments.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
[
{
"id": 1388534400000,
"author": "Pete Hunt",
"text": "Hey there!"
},
{
"id": 1420070400000,
"author": "Paul O’Shannessy",
"text": "React is *great*!"
}
Expand Down
11 changes: 6 additions & 5 deletions public/scripts/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ var CommentBox = React.createClass({
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
Expand Down Expand Up @@ -80,12 +84,9 @@ var CommentBox = React.createClass({

var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment, index) {
var commentNodes = this.props.data.map(function(comment) {
return (
// `key` is a React-specific concept and is not mandatory for the
// purpose of this tutorial. if you're curious, see more here:
// http://facebook.github.io/react/docs/multiple-components.html#dynamic-children
<Comment author={comment.author} key={index}>
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
Expand Down
4 changes: 3 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ import (
"net/http"
"os"
"sync"
"time"
)

type comment struct {
ID int64 `json:"id"`
Author string `json:"author"`
Text string `json:"text"`
}
Expand Down Expand Up @@ -64,7 +66,7 @@ func handleComments(w http.ResponseWriter, r *http.Request) {
}

// Add a new comment to the in memory slice of comments
comments = append(comments, comment{Author: r.FormValue("author"), Text: r.FormValue("text")})
comments = append(comments, comment{ID: time.Now().UnixNano() / 1000000, Author: r.FormValue("author"), Text: r.FormValue("text")})

// Marshal the comments to indented json.
commentData, err = json.MarshalIndent(comments, "", " ")
Expand Down
10 changes: 9 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ app.post('/api/comments', function(req, res) {
process.exit(1);
}
var comments = JSON.parse(data);
comments.push(req.body);
// NOTE: In a real implementation, we would likely rely on a database or
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
// treat Date.now() as unique-enough for our purposes.
var newComment = {
id: Date.now(),
author: req.body.author,
text: req.body.text,
};
comments.push(newComment);
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
if (err) {
console.error(err);
Expand Down
7 changes: 5 additions & 2 deletions server.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,11 @@ function routeRequest()
} elseif (preg_match('/\/api\/comments(\?.*)?/', $uri)) {
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$commentsDecoded = json_decode($comments, true);
$commentsDecoded[] = ['author' => $_POST['author'],
'text' => $_POST['text']];
$commentsDecoded[] = [
'id' => round(microtime(true) * 1000),
'author' => $_POST['author'],
'text' => $_POST['text']
];

$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
file_put_contents('comments.json', $comments);
Expand Down
2 changes: 2 additions & 0 deletions server.pl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

use Time::HiRes qw(gettimeofday);
use Mojolicious::Lite;
use Mojo::JSON qw(encode_json decode_json);

Expand All @@ -22,6 +23,7 @@
if ($self->req->method eq 'POST')
{
push @$comments, {
id => int(gettimeofday * 1000),
author => $self->param('author'),
text => $self->param('text'),
};
Expand Down
5 changes: 4 additions & 1 deletion server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import json
import os
import time
from flask import Flask, Response, request

app = Flask(__name__, static_url_path='', static_folder='public')
Expand All @@ -22,7 +23,9 @@ def comments_handler():
comments = json.loads(file.read())

if request.method == 'POST':
comments.append(request.form.to_dict())
newComment = request.form.to_dict()
newComment['id'] = int(time.time() * 1000)
comments.append(newComment)

with open('comments.json', 'w') as file:
file.write(json.dumps(comments, indent=4, separators=(',', ': ')))
Expand Down
2 changes: 1 addition & 1 deletion server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

if req.request_method == 'POST'
# Assume it's well formed
comment = {}
comment = { id: (Time.now.to_f * 1000).to_i }
req.query.each do |key, value|
comment[key] = value.force_encoding('UTF-8')
end
Expand Down

0 comments on commit aa6e9a8

Please sign in to comment.