Skip to content

Commit 0e7f1b2

Browse files
committedNov 12, 2015
Add ids to data server-side so that keys can be used client-side
1 parent a45fe12 commit 0e7f1b2

File tree

8 files changed

+32
-11
lines changed

8 files changed

+32
-11
lines changed
 

‎comments.json

+2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
[
22
{
3+
"id": 1388534400000,
34
"author": "Pete Hunt",
45
"text": "Hey there!"
56
},
67
{
8+
"id": 1420070400000,
79
"author": "Paul O’Shannessy",
810
"text": "React is *great*!"
911
}

‎public/scripts/example.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ var CommentBox = React.createClass({
4444
},
4545
handleCommentSubmit: function(comment) {
4646
var comments = this.state.data;
47+
// Optimistically set an id on the new comment. It will be replaced by an
48+
// id generated by the server. In a production application you would likely
49+
// not use Date.now() for this and would have a more robust system in place.
50+
comment.id = Date.now();
4751
var newComments = comments.concat([comment]);
4852
this.setState({data: newComments});
4953
$.ajax({
@@ -80,12 +84,9 @@ var CommentBox = React.createClass({
8084

8185
var CommentList = React.createClass({
8286
render: function() {
83-
var commentNodes = this.props.data.map(function(comment, index) {
87+
var commentNodes = this.props.data.map(function(comment) {
8488
return (
85-
// `key` is a React-specific concept and is not mandatory for the
86-
// purpose of this tutorial. if you're curious, see more here:
87-
// http://facebook.github.io/react/docs/multiple-components.html#dynamic-children
88-
<Comment author={comment.author} key={index}>
89+
<Comment author={comment.author} key={comment.id}>
8990
{comment.text}
9091
</Comment>
9192
);

‎server.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,11 @@ import (
2222
"net/http"
2323
"os"
2424
"sync"
25+
"time"
2526
)
2627

2728
type comment struct {
29+
ID int64 `json:"id"`
2830
Author string `json:"author"`
2931
Text string `json:"text"`
3032
}
@@ -64,7 +66,7 @@ func handleComments(w http.ResponseWriter, r *http.Request) {
6466
}
6567

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

6971
// Marshal the comments to indented json.
7072
commentData, err = json.MarshalIndent(comments, "", " ")

‎server.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,15 @@ app.post('/api/comments', function(req, res) {
4242
process.exit(1);
4343
}
4444
var comments = JSON.parse(data);
45-
comments.push(req.body);
45+
// NOTE: In a real implementation, we would likely rely on a database or
46+
// some other approach (e.g. UUIDs) to ensure a globally unique id. We'll
47+
// treat Date.now() as unique-enough for our purposes.
48+
var newComment = {
49+
id: Date.now(),
50+
author: req.body.author,
51+
text: req.body.text,
52+
};
53+
comments.push(newComment);
4654
fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
4755
if (err) {
4856
console.error(err);

‎server.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,11 @@ function routeRequest()
3434
} elseif (preg_match('/\/api\/comments(\?.*)?/', $uri)) {
3535
if($_SERVER['REQUEST_METHOD'] === 'POST') {
3636
$commentsDecoded = json_decode($comments, true);
37-
$commentsDecoded[] = ['author' => $_POST['author'],
38-
'text' => $_POST['text']];
37+
$commentsDecoded[] = [
38+
'id' => round(microtime(true) * 1000),
39+
'author' => $_POST['author'],
40+
'text' => $_POST['text']
41+
];
3942

4043
$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
4144
file_put_contents('comments.json', $comments);

‎server.pl

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
99
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1010

11+
use Time::HiRes qw(gettimeofday);
1112
use Mojolicious::Lite;
1213
use Mojo::JSON qw(encode_json decode_json);
1314

@@ -22,6 +23,7 @@
2223
if ($self->req->method eq 'POST')
2324
{
2425
push @$comments, {
26+
id => int(gettimeofday * 1000),
2527
author => $self->param('author'),
2628
text => $self->param('text'),
2729
};

‎server.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import json
1212
import os
13+
import time
1314
from flask import Flask, Response, request
1415

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

2425
if request.method == 'POST':
25-
comments.append(request.form.to_dict())
26+
newComment = request.form.to_dict()
27+
newComment['id'] = int(time.time() * 1000)
28+
comments.append(newComment)
2629

2730
with open('comments.json', 'w') as file:
2831
file.write(json.dumps(comments, indent=4, separators=(',', ': ')))

‎server.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

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

0 commit comments

Comments
 (0)
Please sign in to comment.