Apiway::Client
instance, personal for each connection;client
method. An array of all connected clients can be obtained by calling Apiway::Client.all
(in addition, this method accepts a block of code applied to each client). # client[:user_id] = 1 # client[:user_id] # > 1
app/base/client.rb
, which allows you to configure client connection / disconnection event handling, as well as receive a new message. Each handler is called in the context of the client whose event is being processed. module Apiway class Client on_connected do # # end on_message do |message| # end on_disconnected do # # end end end
ActiveRecord::Base
when it is generated, but this is not necessary, the main thing is that it be extended by the Apiway::Model
module. This module adds to it the only sync
method, the call of which starts the process of synchronization of resources depending on this model (automatically called on ActiveRecord
models after saving / deleting the model). class Test < ActiveRecord::Base include Apiway::Model end
class UsersController < ApplicationController include Apiway::Controller # Rails # Before- before_action :method_name before_action :method_name, only: :action_name before_action :method_name, only: [ :action_name, :action_name ] before_action :method_name, except: :action_name before_action :method_name, except: [ :action_name, :action_name ] # After- after_action :method_name after_action :method_name, only: :action_name after_action :method_name, only: [ :action_name, :action_name ] after_action :method_name, except: :action_name after_action :method_name, except: [ :action_name, :action_name ] # action :auth do # # Api.query("Users.auth", {name: "Bob", pass: "querty"}) # .then(function( id ){ console.log("User id: ", id) }) # .catch(function( e ){ console.log("Error: ", e) }) begin # params user = User.find_by! name: params[ :name ], pass: params[ :pass ] rescue Exception => e # , error # # , "Error: auth_error" error :auth_error # error , , , # before-, # else # client # ( Apiway::Client), # id client[:user_id] = user.id # # , id # "User id: 1" end end end
# # var userMessages = new Resource("UserMessages", {limit: 30}); # userMessages.onChange(function( data ){ console.log("New data", data) }); # userMessages.onError(function( e ){ console.log("Error", e) }); class UserMessagesResource < ApplicationResource include Apiway::Resource # depend_on Message, User # , Message User, # , # # access do # # client , , # :user_id error :auth_error unless client[:user_id] # error # "error" "auth_error", # "Error: auth_error" , "", # "" , , # "change" # "New data: [{mgs},{mgs},{mgs}...]" end # # , # data do # params Message.find_by(user_id: client[:user_id]).limit(params[:limit]).map do |msg| { text: msg.text, user: msg.user.name } end end end
.on(event, callback[, context]) // callback event; .one(event, callback[, context]) // .on(), ; .off() // ; .off(event) // event; .off(event, callback) // callback event; .off(event, callback, context) // callback event, // context;
Api.connect(address[, options ]) // // : // aliveDelay - ( ) "ping" , , // , Api.query( "Messages.new", params ) // new MessagesController'a // params Api.disconnect() // Api.beforeReadyPromise( callback ) // , (Promise) // // // "ready" - "unready" - // , , // Api.onReady(callback, context) // Api.on("ready", callback, context) Api.oneReady(callback, context) // Api.one("ready", callback, context) Api.offReady(callback, context) // Api.off("ready", callback, context) Api.onUnready(callback, context) // Api.on("unready", callback, context) Api.oneUnready(callback, context) // Api.one("unready", callback, context) Api.offUnready(callback, context) // Api.off("unready", callback, context)
error
method on the server). var resource = new Resource("Messages", {limit: 10}) // MessagesResource {limit: 10} resource.name // resource.data // resource.get("limit") // limit, : 10 resource.set({limit: 20, order: "ask"}) // limit order // resource.unset("order") // order // resource.onChange(callback, context) // resource.on("change", callback, context) resource.oneChange(callback, context) // resource.one("change", callback, context) resource.offChange(callback, context) // resource.off("change", callback, context) resource.onError(callback, context) // resource.on("error", callback, context) resource.oneError(callback, context) // resource.one("error", callback, context) resource.offError(callback, context) // resource.off("error", callback, context)
$ gem install apiway # gem'a $ apiway new Chat # $ cd Chat #
$ bundle exec rake db:create_migration NAME=create_messages
# db/mirgations/20140409121731_create_messages.rb class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.text :text t.timestamps null: true end end end
$ bundle exec rake db:migrate
$ apiway generate model Message
# app/models/message.rb class Message < ActiveRecord::Base include Apiway::Model # # , validates :text, presence: { message: "blank" }, length: { in: 1..300, message: "length" } end
$ apiway generate resource Messages
# app/resources/messages.rb class MessagesResource < ApplicationResource include Apiway::Resource # , Message depend_on Message # , data do Message.limit( params[ :limit ] ).order( created_at: :desc ).reverse.map do |message| { id: message.id, text: message.text } end # params - , , # params = {limit: 10} 10 # [{id: 10, text: "Hello 10"}, {id: 9, text: "Hello 9"}, {id: 8, text: "Hello 8"}, ...] end end
$ apiway generate controller Messages
# app/controllers/messages.rb class MessagesController < ApplicationController include Apiway::Controller # , action :new do begin # params - current_user.messages.create! text: params[ :text ] rescue ActiveRecord::RecordInvalid => e # error e.record.errors.full_messages else true # , end end end
$ apiway server
npm install apiway --save
// source/app.js import { Api, Resource } from "apiway"; // var Chat = { run: function(){ // Messages { limit: 10 } var messagesResource = new Resource( "Messages", { limit: 10 } ); // render messagesResource.onChange( this.render ); // send window window.send = this.send; }, render: function( messages ){ // console.clear(); // messages.forEach( function( item ){ console.log( item.text ) }); }, send: function( text ){ // new Messages Api.query( "Messages.new", { text: text } ) // console.warn .catch( function( errors ){ console.warn( errors.join( ", " ) ) }); } }; Api // .connect( "ws://localhost:3000", { aliveDelay: 5000 } ) // , .oneReady( function( e ){ Chat.run() }); // "" // , onReady(), //
send("Hello world")
and again see the last ten messages, or rather our new and nine previous ones. We try to send an empty message - we see errors. // ./components/Message.jsx import React from "react"; class Message extends React.Component { render(){ return ( <div> <b>{ this.props.data.user }</b> <p>{ this.props.data.text }</p> </div> ); } } export default Message;
// ./components/Chat.jsx import React from "react"; import Message from "./Message.jsx"; import { Api, Resource } from "apiway"; // , // let errorsMsg = { "Text blank": " ", "Text length": " 1 300 " }; class Chat extends React.Component { constructor( props ){ // super( props ); this.state = { messages: [], errors: [] }; } componentDidMount(){ // , // Messages { limit: 30 } this.MessagesResource = new Resource( "Messages", { limit: 30 } ); // this.MessagesResource.onChange(( messages )=>{ this.setState({ messages }) }); // callback } componentWillUnmount(){ // this.MessagesResource.destroy(); } onKeyUp( e ){ // Enter' , if( e.keyCode !== 13) return; // new Messages, {text: " "} Api.query( "Messages.new", { text: e.target.value } ) // (Promise) .then( ()=>{ this.setState({ errors: [] }) }, ( errors )=>{ this.setState({ errors }) }); // - , - } render(){ return ( <div> // <div> { this.state.messages.map( ( message )=>{ return <Message data={ message } key={ message.id } />; } ) } </div> // <input type="text" onKeyUp={ ( e )=> this.onKeyUp( e ) } /> // <div> { this.state.errors.map( function( key ){ return errorsMsg[ key ]; }).join( ", " ) } </div> </div> ); } } export default Chat;
import React from "react"; import Chat from "./components/Chat.jsx"; Api // .connect( `ws://localhost:3000`, { aliveDelay: 5000 } ) .oneReady( function( e ){ // , , React.render( <Chat />, document.getElementById( "app" ) ); });
as_json
method as_json
.messageResource.set({limit: 50})
- the resource will load the last 50 messages and generate the " change " event.Source: https://habr.com/ru/post/268031/
All Articles