Using View and Data API with Meteor

Source: Internet
Author: User

by Daniel Du

I had been studying Meteor these days, and find that Meteor was really a mind-blowing framework, I can talk about the this LAT ter. I was inspired by this question on forum and started to looking at the possibilities of using View and Data APIs in Meteor. Since the "Meteor works is" so different, I had to say that it was not pleasant experience to does 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 HTTP://LM V.meteor.com. In this post I'll write down how I do this, hopefully it's helpful in case you are doing similar stuff.

Firstly I created a Meteor project with the "Meteor create MyProject" command, which creates a "Hello World" project. To make it look nice, I refactored the folder structure according to the document of meteor about file structure 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 is running at client side, "Server" folder contains the scripts which is Running at server side.

To use View and Data APIs, we need to does the authentication process to get access tokens with consumer Key/secret key, whic  H can is applied from http://developer.autodesk.com. The authentication should is done at server side, otherwise your secret key would be peeked by hackers, so I'll do the AU Thentication in "\server\index.js". But first let me add the ' http ' package to send REST request to Autodesk authentication server from meteor. Running command "Meteor add http" from command line, and can also edit "./meteor/packages" File dir Ectly, so this 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 ' would edit this file for you,
# but can also edit it by hand.

meteor-base             # Packages every meteor app Needs to has
mobile-experience       # Packages for a great mobile UX
mongo & nbsp;                 # The Database Meteor supports right now
blaze-html-templates    # Compile. html files into Meteor Blaze view S
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 to clients (for prototyping)

# Allow to send REST calls to authentication server
http

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

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

Meteor.startup (function() {//code to run in server at startup}); Meteor.methods ({getaccesstoken:function() { This. unblock ();varCredentials = {credentials: {//Replace placeholder below by the Consumer Key and Consumer Secret your got from                //Http://developer.autodesk.com/for the production serverClient_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 URLBASEURL:' https://developer.api.autodesk.com ', Version:' v1 '}; Credentials. Authenticationurl = credentials. BASEURL +'/authentication/'+ credentials. Version +'/authenticate '        //must use synchronous mode        varresult = Meteor.http.post (credentials. Authenticationurl, {params: Credentials.credentials});//get the access token object        returnResult.data; }})

Now let's back to the client side, with "/client/viewer/viewer.html" I created a simple template as below:

<template name= "viewer"  >  "viewer"  class  = " Viewer " > </div></template> 

In the "\viewer\viewer.js", I'll 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 the console of developer tool, so far so good.

To the use View and the Data API, we need to the Add reference to viewer JavaScript libraries. It seems a very basic thing but it turns off to being the difficult part while it comes to Meteor. This blog introduced the ways to add a script tags into meteor. I tried this solution by creating a script template and load the ' viewer3d.js ' and viewer style file on the fly I am trying to create a viewer with View and Data JavaScript APIs, 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" have not been loaded yet when I am try ing 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 Descr Ibed on meteor Document:

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

Files in th E lib directory at the root of your application is loaded first.

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

Files in subdirectories is loaded before files in the parent directories, so, files in the deepest subdirectory is Lo Aded first (after Lib), and files in the root directory is loaded last (other than main.*).

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

These rules stack, so-within LIB, for example, files is still loaded in alphabetical order; and if there is mult Iple files named Main.js, the ones in subdirectories is loaded earlier.

So since Viewer JS Lib was loaded very late, I cannot use it in Viewer.js to initialize the viewer. Luckily, I found that if I put the <script src= ""/> tags into

<Head>  <title>Hello</title>  <link rel= "stylesheet" type= "text/css" href = "Https://developer.api.autodesk.com/viewingservice/v1/viewers/style.css" /> < Script src = "Https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js" ></ Script > </Head><Body>  <H1>Welcome to meteor!</H1>{{>Hello}} {{>Viewer}}</Body><Template name= "Hello">  <Button>Click Me</Button>  <P>You ' ve pressed the button {{counter}} times.</P></Template>

OK, with this 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{vartoken = Result.access_token; Console.log (token);//initialize the viewerInitviewer (token); }    });});varInitviewer =function(token) {varDefaulturn =' DXJUOMFKC2SUB2JQZWN0CZPVCY5VYMPLY3Q6BW9KZWWYMDE2LTAXLTI4LTAYLTQ0LTM2LWLKBWPJAJL5ZXLNYZHWN3H5BDBWZXB5DM54OWKVZ2F0ZWHV dxnllm53za== ';if(Defaulturn.indexof (' urn: ')!== 0) Defaulturn =' urn: '+ Defaulturn;functionInitializeviewer (Containerid, DocumentID, role) {varViewercontainer = document.getElementById (Containerid);varViewer =NewAutodesk.Viewing.Private.GuiViewer3D (Viewercontainer);        Viewer.start (); Autodesk.Viewing.Document.load (DocumentID,function(document) {varRootitem = Document.getrootitem ();varGeometryitems = 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);    }        ); }functionInitialize () {varOptions = {env:"Autodeskproduction",//getaccesstoken:gettoken,            //refreshtoken:gettokenAccesstoken:token}; Autodesk.Viewing.Initializer (Options,function() {Initializeviewer (' Viewer ', Defaulturn,' 3d ');    }); }//callInitialize ();}

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

Https://github.com/Developer-Autodesk/meteor-view.and.data.api

Using View and Data API with Meteor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.