博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Using View and Data API with Meteor
阅读量:4548 次
发布时间:2019-06-08

本文共 9181 字,大约阅读时间需要 30 分钟。

By

I have been studying these days, and find that Meteor is really a mind-blowing framework, I can talk about this latter. I was inspired by on forum and started to looking at the possibilities of using View and Data API in Meteor. Since the way of Meteor works is so different, I have to say that it is not pleasant experience to do that especially for a meteor starter like me. Anyway, after struggling for days, trying this and that, I finally made a simple working site and deployed it as . In this post I will write down how I did this, hopefully it is helpful in case you are doing similar stuff.

Firstly I created a Meteor project with “meteor create myproject” command, which creates a “hello world” project. To make it look nice, I refactored the folder structure according to the as below:

.
├── README.md
├── client
│   ├── index.html
│   ├── index.js
│   ├── style.css
│   └── viewer
│       ├── viewer.html
│       └── viewer.js
├── lib
└── server
    └── index.js

The “client” folder contains the contents which are running at client side, “server” folder contains the scripts which are running at server side.

To use View and Data API, we need to do the authentication process to get access token with consumer key/ secret key, which can be applied from .  The authentication should be done at server side, otherwise your secret key will be peeked by hackers, so I will do the authentication in “\server\index.js”. But first let me add the “http” package to send REST request to Autodesk authentication server from meteor. You can do this by running command “meteor add http” from command line, and you can also edit “./meteor/packages” file directly, so here is my packages file:

===========================

# Meteor packages used by this project, one per line.

# Check this file (and the other files in this directory) into your repository.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.

meteor-base             # Packages every Meteor app needs to have

mobile-experience       # Packages for a great mobile UX
mongo                   # The database Meteor supports right now
blaze-html-templates    # Compile .html files into Meteor Blaze views
session                 # Client-side reactive dictionary for your app
jquery                  # Helpful client-side library
tracker                 # Meteor's client-side reactive programming library

standard-minifiers      # JS/CSS minifiers run for production mode

es5-shim                # ECMAScript 5 compatibility for older browsers.
ecmascript              # Enable ECMAScript2015+ syntax in app code

autopublish             # Publish all data to the clients (for prototyping)

insecure                # Allow all DB writes from clients (for prototyping)

# Allow to send REST calls to authentication server

http

=============================

With that, I can add a Meteor method to do authentication from “/server/index.js”,. It can be called from client side with “Meteor.call()”. Here is the code snippet, please note that I am using synchronous mode when doing “Meteor.http.post”, as I found that I cannot get the returned access token from client side afterwards if I use async mode.

Meteor.startup(function () {    // code to run on server at startup});Meteor.methods({    getAccessToken: function () {        this.unblock();        var credentials = {            credentials: {                // Replace placeholder below by the Consumer Key and Consumer Secret you got from                // http://developer.autodesk.com/ for the production server                client_id: process.env.CONSUMERKEY || 'replace with your consumer key',                client_secret: process.env.CONSUMERSECRET || 'your secrete key',                grant_type: 'client_credentials'            },            // If you which to use the Autodesk View & Data API on the staging server, change this url            BaseUrl: 'https://developer.api.autodesk.com',            Version: 'v1'        };        credentials.AuthenticationURL = credentials.BaseUrl + '/authentication/' + credentials.Version + '/authenticate'        //must use synchronous mode        var result = Meteor.http.post(            credentials.AuthenticationURL,            {
params: credentials.credentials} ); //get the access token object return result.data; }})

 

Now let’s back to the client side, in “/client/viewer/viewer.html” I created a simple template as below:

In the “\viewer\viewer.js”, I will try to get the access token first with following code: 

Template.viewer.onCreated(function(){    //console.log('viewer template created.')    Meteor.call('getAccessToken', function (error, result) {        if (error) {            console.log(error);        }        else {            var token = result.access_token;            console.log(token);            //initialize the viewer            initViewer(token);        }    });});

When the viewer template is created, I call to the server side meteor method to do authentication and get the access token, once I get the access token, I can initialize a viewer at client side with View and Data JavaScript API. Now I can see the token from console of developer tool, so far so good.

 

To use View and Data API, we need to add reference to viewer JavaScript libraries. It seems a very basic thing but it turns out to be the difficult part when it comes to Meteor. introduced two ways to add a script tag into meteor. I tried this solution by creating a script template and load the “viewer3d.js” and viewer style file on the fly, but when I am trying to create a viewer with View and Data JavaScript API, I run to the problem as described in the forum post:

"Uncaught ReferenceError: AutodeskNamespace is not defined"

If I examined to the network tab of browser development tool, the “viewer3d.min.js” has not been loaded yet when I was trying to use it.

Meteor controls the load process of JS files and it is not easy to control the load order, here is the load order as described on meteor document:

The JavaScript and CSS files in an application are loaded according to these rules:

Files in the lib directory at the root of your application are loaded first.

Files that match main.* are loaded after everything else.

Files in subdirectories are loaded before files in parent directories, so that files in the deepest subdirectory are loaded first (after lib), and files in the root directory are loaded last (other than main.*).

Within a directory, files are loaded in alphabetical order by filename.

These rules stack, so that within lib, for example, files are still loaded in alphabetical order; and if there are multiple files named main.js, the ones in subdirectories are loaded earlier.

So since viewer js lib is loaded very late, I cannot use it in viewer.js to initialize the viewer. Luckily, I found that if I put the <script src=””/> tag into <head>, it will be loaded first, so in “/client/index.html”:

  hello    

Welcome to Meteor!

{
{
> hello}} {
{
> viewer }}

 

OK, with that I can initialized viewer in “/client/viewer/viewer.js” file, the code snippet is below:

Template.viewer.onCreated(function(){    //console.log('viewer template created.')    Meteor.call('getAccessToken', function (error, result) {        if (error) {            console.log(error);        }        else {            var token = result.access_token;            console.log(token);            //initialize the viewer            initViewer(token);        }    });});var initViewer = function (token) {    var defaultUrn = 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWwyMDE2LTAxLTI4LTAyLTQ0LTM2LWlkbWpjajl5ZXlnYzhwN3h5bDBwZXB5dm54OWkvZ2F0ZWhvdXNlLm53ZA==';    if (defaultUrn.indexOf('urn:') !== 0)        defaultUrn = 'urn:' + defaultUrn;    function initializeViewer(containerId, documentId, role) {        var viewerContainer = document.getElementById(containerId);        var viewer = new Autodesk.Viewing.Private.GuiViewer3D(            viewerContainer);        viewer.start();        Autodesk.Viewing.Document.load(documentId,            function (document) {                var rootItem = document.getRootItem();                var geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(                    rootItem,                    { 'type': 'geometry', 'role': role },                    true);                viewer.load(document.getViewablePath(geometryItems[0]));            },            // onErrorCallback            function (msg) {                console.log("Error loading document: " + msg);            }        );    }    function initialize() {        var options = {            env: "AutodeskProduction",            //getAccessToken: getToken,            //refreshToken: getToken            accessToken : token        };        Autodesk.Viewing.Initializer(options, function () {            initializeViewer('viewer', defaultUrn, '3d');        });    }    //call    initialize();}

Now I have a running meteor application with viewer embedded. I also posted my sample on github, so you may want to take a look to check the complete code. Hope it helps some.

转载于:https://www.cnblogs.com/junqilian/p/5173884.html

你可能感兴趣的文章
规范 : Sql statusEnum
查看>>
jQuery的.live()和.die() 使用介绍
查看>>
mybatis
查看>>
我该怎么安排下属的工作-项目经理如何分配任务
查看>>
Chord算法(原理)
查看>>
cocos2d-html5
查看>>
Ubuntu 14.04 Android 使用Maven二 创建自己的Mavenproject
查看>>
SSI框架中配置log4j
查看>>
向ASP.NET MVC控制器传递JSON对象的方法
查看>>
不变模式
查看>>
RabbitMQ安装与搭建
查看>>
【转】UITextView检查已输入字符字数
查看>>
延迟初始化
查看>>
字符串格式化和format
查看>>
页面内容添加新的显示或者显示隐藏的内容,滚动条滚动到最低端,显示出新内容...
查看>>
【poj1182】 食物链
查看>>
Oracle学习之start with...connect by子句的用法
查看>>
matlab去云雾
查看>>
500lines项目简介
查看>>
Asp.net core logging 日志
查看>>