RUBY Sinatra API를 사용한 CRUD 반응


Ruby Sinatra는 Ruby on Rails의 작은 대안으로, 2007년에 만들어지고 오픈 소스화되었으며 Apple, LinkedIn 및 GitHub와 같은 회사에서 사용되었습니다. 이 '마이크로프레임워크'는 최소한의 노력으로 기능적인 백엔드에서 프런트엔드 인터페이스로 만드는 데 중점을 둡니다. REACT와 함께 사용하면 CRUD(만들기, 읽기, 업데이트, 삭제) 작업 중에 조작 및 디버그하는 것이 상당히 고통스러울 수 있습니다.

예를 들어 GitHub에서 이 repo를 포크하고 복제하는 경우 터미널 내에서 'bundle install' 명령을 실행한 후 다양한 다른 gem 중에서 ActiveRecordSinatra으로 파일 구조가 설정됩니다. . 이것은 creating a REACT APP과 쌍을 이루어 전체 스택 웹 응용 프로그램을 시작하는 데 필요한 모든 파일 구조를 제공합니다. 아래의 CRUD에 대한 설명에서는 마이그레이션 생성, 데이터 시드, Sinatra 내에서 백엔드 서버 실행, 프런트 엔드 인터페이스 구축 및 REACT 애플리케이션에서 브라우저 실행 경험이 있다고 가정합니다. 이러한 모든 작업의 ​​예는 thisfrontend repo 및 thisbackend repo 에서 찾을 수 있습니다. 둘 다 내 코딩 부트캠프 내 그룹 프로젝트를 위해 함께 작동하도록 빌드되었습니다.

아래 예제는 React 프런트 엔드에서 Sinatra 백엔드로의 CRUD 작업에 대한 것입니다. 이러한 예는 프런트엔드 및 백엔드 리포지토리 내에서 사용되는 것과는 다르며 이 프로젝트 내에서 사용되는 기능 및 작업에 대한 자세한 설명으로 사용됩니다.

생성(POST)

//REACT FRONTEND
//Callback function to handle post request from client
//has new blog post object passed as parameters(name doesn't matter)
 function addBlog(newBlog) {
//Server URL with appropriate request endpoint
    fetch('http://localhost:9292/blog_post', {
//method stated for server.
      method: 'POST',
//headers clarify what type of content is being passed through request.
      headers: { 'Content-Type': 'application/json' },
//body turns object to string format for backend readability, 
//object has keys(params in ruby) that match columns for blogs table.
// newBlog will be destructured
// and 'POST'ed to backend before being returned.
      body: JSON.stringify(newBlog)
    }).then(r => r.json())
//returned data sets state variable to be all blogs
//including newly posted blog.
.then(data => setBlogs(data))
  };



#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to all blog posts
post '/blog_post' do

#creates new instance of a Blog for the Blog class and blogs table.
   Blog.create(title: params[:title],
                content: params[:content], 
                author: params[:author])
    # return all blog posts as well as newly posted one.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end


읽기(GET)

//REACT FRONTEND
//React component mounts, useEffect runs a GET request to
//the Sinatra API.
 useEffect(()=> {
//Server URL with appropriate request endpoint
    fetch('http://localhost:9292/blog_post')
.then(r => r.json())
//returned data sets state variable to be all blogs
.then(data => setBlogs(data))
  },
 []);



#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to all blog posts
get '/blog_post' do
    # return all blog posts after request
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end


업데이트(패치)

//REACT FRONTEND
//Callback function to handle patch request from client
//has new blog post object passed as parameters(name doesn't matter)
 function editBlog(blog,id) {
//Server URL with appropriate request endpoint
    fetch(`http://localhost:9292/blog_post/${id}`, {
//method stated for server.
      method: 'PATCH',
//headers clarify what type of content is being passed through request.
      headers: { 'Content-Type': 'application/json' },
//body turns object to string format for backend readability, 
//object has keys(params in ruby) that match columns for blogs table.
// blog will be destructured
// and 'PATCH'ed over in backend before being returned.
      body: JSON.stringify(blog)
    }).then(r => r.json())
//returned data sets state variable to be all blogs
//including updated(PATCHed) blog.
.then(data => setBlogs(data))
  };



#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to specific blog post with ':id'
patch '/blog_post/:id' do

#finds appropriate blog post using :id endpoint
 update_blog = Blog.find(params[:id])
#updates the blog instance to requested params.
  update_blog.update(title: params[:title],
                content: params[:content], 
                author: params[:author])
    # return all blog posts as well as newly patched one.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end


삭제(DELETE)

//REACT FRONTEND
//Callback function to handle delete request from client
//has blog post object passed as parameters(name doesn't matter)
 function editBlog(blog,id) {
//Server URL with appropriate request endpoint
    fetch(`http://localhost:9292/blog_post/${id}`, {
//method stated for server.
      method: 'DELETE',
//headers and body not necessary for DELETE request
    }).then(r => r.json())
//returned data logged to console
//including updated(PATCHed) blog.
.then(data => console.log(data)
  };



#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to specific blog post with ':id'
delete '/blog_post/:id' do

#finds appropriate blog post using :id endpoint
 blog = Blog.find(params[:id])
#Destroys instance of Blog found from blogs table and class
    # return all blog posts, with deleted blog no longer there.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end


이러한 링크와 CRUD 예제가 귀하와 귀하의 전체 스택 애플리케이션 노력에 도움이 되었기를 바랍니다. 프로젝트 링크는 프로젝트JaneAmy에서 일하는 다른 사람들의 도움 없이는 가능하지 않을 것입니다. 두 사람 모두 뛰어난 웹 개발자입니다. 그들의 GitHub 프로필과 리포지토리 및 mine을 자유롭게 확인하십시오. 행복한 개발!

좋은 웹페이지 즐겨찾기