appbase_实时图形数据库即服务与Appbase

appbase

介绍 (Introduction)

As developers, we all know that our industry evolves at a very fast pace. So fast that it's often hard to keep up with all the new libraries, frameworks, and new versions of the tools we use daily. In some roles, it's important to stay on top of industry news and trends. This post brings to you a new database concept for you to get started with and make your learning experience more effective and easier.

作为开发人员,我们都知道我们的行业发展非常Swift。 如此之快,以至于很难跟上我们每天使用的所有新库,框架和工具的新版本。 在某些角色上,紧跟行业新闻和趋势很重要。 这篇文章为您带来了一个新的数据库概念,供您入门,并使您的学习体验更有效,更轻松。

A trend that has already started taking shape is the concept of database-as-a-service (DBaaS). There are many hosted services out there.

数据库即服务(DBaaS)的概念已经开始形成一种趋势。 那里有很多托管服务。

In this article, I’ll cover a realtime graph database, which is worth keeping an eye on. It's a DBaaS product that handles database management and optimization for users: AppBase.

在本文中,我将介绍一个实时图形数据库 ,值得关注。 这是一种DBaaS产品,可为用户处理数据库管理和优化: AppBase

appbase

As a service, Appbase handles your database backend and does the dirty work of database management for you.

作为一项服务, Appbase可以处理您的数据库后端,并为您完成数据库管理的繁琐工作。

They use a REST (representational state transfer) API that can be used from any platform. The REST API basically acts as a two-way street to get data in and out. Also this platform is naturally designed to handle multi tenancy, meaning the ability to handle separate groups of users who share access to the databases.

他们使用可以在任何平台上使用的REST(表示状态传输)API。 REST API基本上是一条双向路以获取数据。 同样,该平台自然设计为可以处理多租户,这意味着可以处理共享数据库访问权限的不同用户组。

概念 (Concepts)

Several popular databases can be classified as below:

几个受欢迎的数据库可以分类如下:

AppBase is a realtime Directed Graph Database, built on top of a graph schema, where objects are called Vertices (a graph term for entities), and the links (relationships) between the objects are called Edges.

AppBase是一个实时有向数据库,建立在图模式之上,其中对象称为Vertices (实体的图形术语),而对象之间的链接(关系)称为Edges

We can not actually compare these concepts with other kinds of databases, but it helps to understand if we compare the usage practices. For instance, SQL has concepts for table, row, column, relation and MongoDB has collection, Document, and fields, here are the key concepts in AppBase:

我们实际上无法将这些概念与其他类型的数据库进行比较,但是有助于了解我们是否可以比较使用习惯 。 例如,SQL具有tablerowcolumnRelationship的概念,而MongoDB具有collectionDocumentfields ,这是AppBase中的关键概念:

  1. Vertex — is similar to a Document in MongoDB, it stores data.

    • key — A string that is used to access the vertex as an entry point.
    • properties — A JSON object representing the data inside the vertex.

    顶点 -类似于MongoDB中的文档,它存储数据。

    • key —用于访问顶点作为入口点的字符串。
    • properties —表示顶点内部数据的JSON对象。
  2. Namespace — is similar to a Collection in MongoDB or type in ElasticSearch. A vertex always belongs to a namespace and security rules can be applied on namespaces.

    命名空间 -类似于或Collection MongoDB中键入 ElasticSearch。 顶点始终属于名称空间,并且安全规则可以应用于名称空间。

  3. Edge — is a directional link to another vertex.

    • priority — An edge can optionally have a priority, a Number (a secondary index).
    • outVertex — is the vertex which the edge points to.
    • inVertex — the vertex from which the edge starts.
    • i.e. an edge is pointed from inVertex to an outVertex.

    边缘 —是到另一个顶点的定向链接。

    • 优先级—边缘可以选择具有优先级,即数字(二级索引)。
    • outVertex —是边指向的顶点。
    • inVertex —边缘开始的顶点。
    • 即,一条边从inVertex指向outVertex。
  4. Path — it is a powerful way to point to the exact data you want to interact with. A typical path looks like <namespace>/<v1>/<v2>/…/<vn>/.

    路径 -这是指向要与之交互的确切数据的有效方法。 典型路径类似于<namespace>/<v1>/<v2>/…/<vn>/

  5. URL — It is just another representation of a Path prefixed with the Appbase API base URL, application’s name and the API version. A way to point to a Path in the REST API. Eg. https://api.appbase.io/<app_name>/v2/<path>/.

    URL —这是Path的另一种表示形式,前缀为Appbase API基本URL,应用程序的名称和API版本。 指向REST API中的路径的方法。 例如。 https://api.appbase.io/<app_name>/v2/<path>/

(Example)

This example will use a graph visualization tool for drawing directed graphs and use AppBase as a realtime database for storing and fetching data.

本示例将使用图形可视化工具绘制有向图,并将AppBase用作用于存储和获取数据的实时数据库。

There are some editing tools for building directed graphs, for instance, Force Editor includes pan and zoom functions. Also it enables the user to drag from an existing node to add a new node/link and drag the nodes to move the graph dynamically.

有一些用于构建有向图的编辑工具,例如, Force Editor包括平移和缩放功能。 它还使用户能够从现有节点上拖动以添加新的节点/链接,并拖动节点以动态移动图形。

Force Editor is based on another open source D3.js.The D3.js library offers many ways to visualize the relationships between nodes. The purpose is to position the nodes of a graph in two-dimensional space in a simple, intuitive, and aesthetically pleasing way.

Force Editor基于另一个开源D3.js.D3.js库提供了许多可视化节点之间关系的方法。 目的是以一种简单,直观且美观的方式将图的节点定位在二维空间中。

image that ilustrates Force Editor

Drag from an existing node to add a new node or link. Click to select/deselect nodes/links. Hit the DELETE key to remove the selected node or link. Drag to pan. Scroll to zoom.

从现有节点拖动以添加新节点或链接。 单击以选择/取消选择节点/链接。 按DELETE键以删除选定的节点或链接。 拖动以平移。 滚动以缩放。

如何设置AppBase (How to set up AppBase)

It can be used either on the backend or on the client side. To use it in the browser, use this link: https://cdn.appbase.io/latest/appbase.js. To use it with nodejs, do npm install appbasejs. It will be exposed as a global object Appbase and has the following four methods: credentials(), ns(), uuid(), and serverTime(). Each methods will be described later.

它既可以在后端使用,也可以在客户端使用。 要在浏览器中使用它,请使用以下链接: https://cdn.appbase.io/latest/appbase.js : https://cdn.appbase.io/latest/appbase.js 。 要将其与nodejs一起使用,请执行npm install appbasejs 。 它将作为全局对象Appbase公开,并具有以下四个方法: certificate credentials()ns()uuid()serverTime() 。 每种方法将在后面描述。

First step to getting started with is log in to Dashboard, and create a new app. To set it up, you have to authorize the app using credentials method and providing the appname and appsecret identifiers, as they appear in the Dev Console.

入门的第一步是登录Dashboard ,然后创建一个新应用。 要进行设置,您必须使用credentials方法授权应用程序,并提供在开发控制台中显示的appnameappsecret标识符

Appbase.credentials('aphrodite',
'4d8d0072580912343cd74aa0015cd217',
function(error, isAuthorized) {
  if (!error && isAuthorized)
    console.log("app successfully registered");
});

Note: you will wanna change the parameters of the Appbase.credentials() method to your own app name, app secret combination, as seen in the Dashboard.

注意:您想要将Appbase.credentials()方法的参数更改为您自己的应用程序名称 ,即应用程序秘密组合 ,如仪表板所示

OAuth is another manner to make authentication easy with completely client-side code. It has built-in functionality for third-party providers such as Facebook, LinkedIn, GitHub, Dropbox, and Google. When a user authenticates to, the information about the user is returned in callbacks on the client device. Once authenticated, the user session will be managed, ensuring that the user is remembered across page refreshes and browser restarts.

OAuth是另一种通过完全客户端代码使身份验证变得容易的方式。 它具有面向第三方提供商(例如Facebook,LinkedIn,GitHub,Dropbox和Google)的内置功能。 当用户进行身份验证时,有关该用户的信息将在客户端设备上的回调中返回。 一旦通过身份验证,将管理用户会话,确保在刷新页面和重新启动浏览器时记住用户。

To enable OAuth login is needed few initial steps. These steps will not be covered here, you can read further details at this link.

要启用OAuth登录,只需几个初始步骤。 这些步骤将不在此处介绍,您可以在此链接上阅读更多详细信息。

After enabling it, the following code shows a popup and retrieves the user’s credentials for Appbase, and Facebook.

启用它之后,以下代码将显示一个弹出窗口,并检索Appbase和Facebook的用户凭据。

Appbase.authPopup('facebook', function(error, authObj, requestObj) {
  if(error) {
    console.log('Error occured:', error);
  } else {
    console.log('Logged in as:', authObj.uid); 
  }
});

requestObj returned in the authentication can be used to perform API calls to a provider. It contains methods that wrap the usual HTTP methods: .get(), .post(), .put(), .patch(), and .del().

身份验证中返回的requestObj可用于执行对提供者的API调用。 它包含包住通常HTTP方法的方法: .get() .post() .put() .patch().del()

Once the user logs in with a provider, the credentials are cached in localStorage automatically, and this helps staying logged in across browser restarts.

用户通过提供程序登录后,凭据将自动缓存在localStorage中,这有助于在重新启动浏览器时保持登录状态。

设置我们的例子 (Setting up our example)

This example is basically client side code. The authentication uses Facebook provider. You can grab the entire example files from my repository. The server in the repository is just to server static files over HTTP.

这个例子基本上是客户端代码。 身份验证使用Facebook提供程序。 您可以从我的存储库中获取整个示例文件。 存储库中的服务器仅用于通过HTTP服务器静态文件。

In JS folder, you can find login.js, file responsible to authenticate via OAuth. Let's take a look on that and see how it's set up.

在JS文件夹中,您可以找到login.js文件,该文件负责通过OAuth进行身份验证。 让我们来看看它是如何设置的。

define(['jquery', 'forceView'], function($, forceView) {
  return function(e, callback) {
    Appbase.credentials("sample_app_with_d3");
    Appbase.authPopup('facebook', function(error, authObj, requestObj) {
      if(error) {
        console.log('Error occured:', error);
      } else {
        console.log('Logged in as:', authObj.uid);
        $(".row.login").hide();
        $('.row.force-view').removeClass('hidden');
        forceView.init(authObj.name);
        require(['observeNS'], function(Observe) {
          Observe.init(authObj);
        });
      }
      callback && callback(error, authObj, requestObj);
    });
  };
});

Once the user log in, OAuth callback will be triggered and do the following:

用户登录后,将触发OAuth回调并执行以下操作:

  1. Hide login form

    隐藏登录表格
  2. Show Force Editor

    显示力编辑器
  3. Init all nodes from user namespace

    从用户名称空间初始化所有节点
  4. Observe and watch for further new user namespaces

    观察并注意其他新的用户名称空间

To see a live example in action, go to https://sample-appbase-with-d3.herokuapp.com/ and click on Enter via Facebook Auth or Enter via appsecret identifier button.

要查看实际示例,请访问https://sample-appbase-with-d3.herokuapp.com/,然后单击“ 通过Facebook Auth 输入”“通过appsecret标识符输入”按钮。

LogIn page

After entering in, open a new window and see how both windows are synced.

输入后,打开一个新窗口,查看两个窗口如何同步。

after the logging in

The graph drawing is up to D3.js but notice the vertice content and edges are the same on both windows.

该图形最多可绘制D3.js,但请注意,两个窗口上的顶点内容和边均相同。

sync cross windows

存储和检索数据 (Storing and retrieving data)

Let's learn how to create two vertices under a namespace user.

让我们学习如何在命名空间user下创建两个顶点。

var authorRef = Appbase.ns('user').v('igor');
var readerRef = Appbase .ns('user').v(Appbase.uuid());

Namespaces are containers that do not hold actual data, but help with data logic separation. A vertex can only be created using a ns reference object.

命名空间是不保存实际数据,但有助于数据逻辑分离的容器。 只能使用ns参考对象创建顶点

As seen here, vertex takes a String as an identifier. Appbase.uuid() is a handy way for creating a unique String id.

如此处所示,顶点将字符串作为标识符。 Appbase.uuid()是创建唯一String ID的便捷方法。

A vertex can store data as a JSON object using the setData() method.

顶点可以使用setData()方法将数据存储为JSON对象。

authorRef.setData({ status: 'geek', location: 'Belo Horizonte, Brazil' });
readerRef.setData({ status: 'learning', message: 'Remember Red, tweet this blog is a good thing.' });

Vertices can be connected via edges. Now let's add readerRef as an edge to the authorRef vertex.

顶点可以通过边连接。 现在让我们将readerRef添加为authorRef顶点的边缘。

authorRef.setEdge('friendship', readerRef);

Now, the readerRef vertex can also be accessed using the path /user/igor/friendship. To retrieve a vertex reference at a given path, ns.v(path) is a handy method.

现在,还可以使用路径/user/igor/friendship来访问readerRef顶点。 要检索给定路径上的顶点参考, ns.v(path)是一种便捷的方法。

Retrieval objects is supported using realtime streams. Just add listeners, which return existing data stored, and keeps returning new data as it keeps changing. Similarly let's add a listener for retrieving edges on the vertex.

使用实时流支持检索对​​象。 只需添加侦听器,这些侦听器将返回存储的现有数据,并随着数据的不断变化而不断返回新数据。 同样,让我们​​添加一个侦听器以检索顶点上的边。

authorRef.on('properties', function(error, ref, authorSnap) {
  console.log(authorSnap.properties().status);
  console.log(authorSnap.properties().location);
});
authorRef.on('edge_added', function(error, outVertexRef, readerSnap) {
  console.log(readerSnap.properties().message);
});

Simple as that! Now you can be confident to come back to the example and understand how Appbase and Force Editor are being integrated on our example.

就那么简单! 现在,您可以自信地回到示例并了解如何将Appbase和Force Editor集成到我们的示例中。

Appbase和Force Editor集成 (Appbase and Force Editor integration)

The integration uses the topic-based publish/subscribe library PubSubJS. It has synchronisation decoupling, so topics are published asynchronously. This helps keep the integration in our example predictable.

集成使用基于主题的发布/订阅PubSubJS 。 它具有同步解耦功能 ,因此主题可以异步发布。 这有助于使我们示例中的集成可预测。

There two cases in that integration. One for listening changes from DBaaS and then apply these changes in Force Editor. And the second case is send changes from Force Editor to DBaaS.

集成中有两种情况。 一种用于监听来自DBaaS的更改,然后在Force Editor中应用这些更改。 第二种情况是将更改从Force Editor发送到DBaaS。

Take a look on the first case below. There is a listener on the Appbase namespace to observe when a vertex is added. Once it detected a new vertex, it will publish a message to Force Editor and the node will be visually added.

看下面的第一种情况。 Appbase名称空间上有一个侦听器,用于观察何时添加顶点。 一旦检测到新顶点,它将向Force Editor发布消息,并且将在视觉上添加该节点。

appbaseSync.js

appbaseSync.js

nsref.on('vertex_added', function(err, vertexRef, obj) {
  /** … **/
  PubSub.publish('forceView:addNode', $.extend(obj.properties() || {}, {
    id: vertexRef.name()
  }));
  /** **/
});

force_view.js

force_view.js

PubSub.subscribe('forceView:addNode', function(msg, node) {
  var selected_node = searchNode(node);
  if (!selected_node) {
    nodes.push(node);
    redraw();
  }
});

Let’s take a look on the second case when the user add a node in Force Editor and it sends a message to store this node accordingly in the DB.

让我们看一下第二种情况,当用户在Force Editor中添加一个节点并发送一条消息以将该节点相应地存储在DB中时。

force_view.js

force_view.js

function mouseup() {
  /** … **/
  PubSub.publish('forceView:addedNode', node);
  /** … **/
  redraw();
}

appbaseSync.js

appbaseSync.js

$('button.add-node').on('click', function() {
  PubSub.publish('forceView:addedNode', {});
});
PubSub.subscribe('forceView:addedNode', function(msg, node) {
  var id = Appbase.uuid(), vref = nsref.v(id);
  node.id = id;
  vref.setData(node);
});

在本地运行示例 (Running the example locally)

You can access the full example application code on Github, just clone the repository git clone git@github.com:igorlima/sample_appbase_with_d3.git (or download the code), execute npm install from a console to install all dependencies, then execute node server.js to start the application! Head to http://localhost:5000 to see the application in action!

您可以在Github上访问完整的示例应用程序代码 ,只需克隆存储库git clone git@github.com:igorlima/sample_appbase_with_d3.git (或下载代码),从控制台执行npm install来安装所有依赖项,然后执行node server.js启动应用程序! 前往http:// localhost:5000查看实际应用程序!

NOTE: Remeber you are using my application sample_app_with_d3. Appbase is completely free up to 100 thousand API calls per month. Feel free to use it while you're learning. After that, create your own application's name, then new learners can use my API calls left. Thanks.

注意:请记住您正在使用我的应用程序sample_app_with_d3 。 Appbase完全免费,每月最多10万个API调用。 在学习时随时使用它。 之后,创建您自己的应用程序名称,然后新学习者可以使用剩下的我的API调用 。 谢谢。

结论 (Conclusion)

That's all there is to it! Just remember the Appbase is a cloud service that lets developers build realtime apps with awesome collaboration and search features. Whether or not it's a new option you have as DBaaS and it can be used either on the backend or on the client side; Also, you now have an additional nugget of knowledge in your tool belt for mastering the data storage.

这里的所有都是它的! 请记住,Appbase是一项云服务,开发人员可以使用它提供出色的协作和搜索功能来构建实时应用。 它是否是DBaaS的一个新选项,并且可以在后端或客户端使用。 而且,您现在在工具带中还拥有其他知识点,可以掌握数据存储。

Appbase is not open-source, yet. They are thinking about the best way to balance their business interests with developer freedom. If you think Appbase should be open source, feel free and write them at info@appbase.io

Appbase尚未开源。 他们正在考虑平衡业务利益和开发人员自由的最佳方法。 如果您认为Appbase应该是开源的,请放心并在info@appbase.io上编写它们

翻译自: https://scotch.io/tutorials/real-time-graph-database-as-a-service-with-appbase

appbase

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值