React 16x - قسمت 22 - ارتباط با سرور - بخش 1 - برپایی تنظیمات
نویسنده: وحید نصیری
تاریخ: ۱۳۹۸/۰۹/۱۸ ۱۴:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
namespace sample_22_backend.Models
{
public class Post
{
public int Id { set; get; }
public string Title { set; get; }
public string Body { set; get; }
public int UserId { set; get; }
}
} using System;
using System.Collections.Generic;
using System.Linq;
using sample_22_backend.Models;
namespace sample_22_backend.Services
{
public interface IPostsDataSource
{
List<Post> GetAllPosts();
bool DeletePost(int id);
Post AddPost(Post post);
bool UpdatePost(int id, Post post);
Post GetPost(int id);
}
/// <summary>
/// هدف صرفا تهیه یک منبع داده آزمایشی ساده تشکیل شده در حافظه است
/// </summary>
public class PostsDataSource : IPostsDataSource
{
private readonly List<Post> _allPosts;
public PostsDataSource()
{
_allPosts = createDataSource();
}
public List<Post> GetAllPosts()
{
return _allPosts;
}
public Post GetPost(int id)
{
return _allPosts.Find(x => x.Id == id);
}
public bool DeletePost(int id)
{
var item = _allPosts.Find(x => x.Id == id);
if (item == null)
{
return false;
}
_allPosts.Remove(item);
return true;
}
public Post AddPost(Post post)
{
var id = 1;
var lastItem = _allPosts.LastOrDefault();
if (lastItem != null)
{
id = lastItem.Id + 1;
}
post.Id = id;
_allPosts.Add(post);
return post;
}
public bool UpdatePost(int id, Post post)
{
var item = _allPosts
.Select((pst, index) => new { Item = pst, Index = index })
.FirstOrDefault(x => x.Item.Id == id);
if (item == null || id != post.Id)
{
return false;
}
_allPosts[item.Index] = post;
return true;
}
private static List<Post> createDataSource()
{
var list = new List<Post>();
var rnd = new Random();
for (var i = 1; i < 10; i++)
{
list.Add(new Post { Id = i, UserId = rnd.Next(1, 1000), Title = $"Title {i} ...", Body = $"Body {i} ..." });
}
return list;
}
}
} using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using sample_22_backend.Models;
using sample_22_backend.Services;
namespace sample_22_backend.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class PostsController : ControllerBase
{
private readonly IPostsDataSource _postsDataSource;
public PostsController(IPostsDataSource postsDataSource)
{
_postsDataSource = postsDataSource;
}
[HttpGet]
public ActionResult<List<Post>> GetPosts()
{
return _postsDataSource.GetAllPosts();
}
[HttpGet("{id}")]
public ActionResult<Post> GetPost(int id)
{
var post = _postsDataSource.GetPost(id);
if (post == null)
{
return NotFound();
}
return Ok(post);
}
[HttpDelete("{id}")]
public ActionResult DeletePost(int id)
{
var deleted = _postsDataSource.DeletePost(id);
if (deleted)
{
return Ok();
}
return NotFound();
}
[HttpPost]
public ActionResult<Post> CreatePost([FromBody]Post post)
{
post = _postsDataSource.AddPost(post);
return CreatedAtRoute(nameof(GetPost), new { post.Id }, post);
}
[HttpPut("{id}")]
public ActionResult<Post> UpdatePost(int id, [FromBody]Post post)
{
var updated = _postsDataSource.UpdatePost(id, post);
if (updated)
{
return Ok(post);
}
return NotFound();
}
}
}
> create-react-app sample-22-frontend > cd sample-22-frontend > npm start
> npm install --save bootstrap
import "bootstrap/dist/css/bootstrap.css";
import "./App.css";
import React, { Component } from "react";
class App extends Component {
state = {
posts: []
};
handleAdd = () => {
console.log("Add");
};
handleUpdate = post => {
console.log("Update", post);
};
handleDelete = post => {
console.log("Delete", post);
};
render() {
return (
<React.Fragment>
<button className="btn btn-primary mt-1 mb-1" onClick={this.handleAdd}>
Add
</button>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.posts.map(post => (
<tr key={post.id}>
<td>{post.title}</td>
<td>
<button
className="btn btn-info btn-sm"
onClick={() => this.handleUpdate(post)}
>
Update
</button>
</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={() => this.handleDelete(post)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</React.Fragment>
);
}
}
export default App;
> npm install --save axios
services.AddTransient<IPostsDataSource, PostsDataSource>();