Coder Social home page Coder Social logo

autodesk-forge / forge-api-nodejs-client Goto Github PK

View Code? Open in Web Editor NEW
123.0 21.0 87.0 4.8 MB

Forge Node.js SDK: Provides Node.js SDK to help you easily integrate Forge REST APIs into the application

License: Apache License 2.0

JavaScript 99.95% Shell 0.05%

forge-api-nodejs-client's Introduction

Forge Node.js SDK Build Status

Forge API: oAuth2 Data-Management OSS Model-Derivative

NOTE: The Design Automation v2 API is deprecated in this module. Instead move to the Design Automation v3 API using this NPM package

This Version includes Data Management filters and pagination, and the Data Management 'Commands' API.

Overview

This Node.js SDK enables you to easily integrate the Forge REST APIs into your application, including OAuth, Data Management, Model Derivative,

Requirements

  • Node.js version 10.12 and above.
  • A registered app on the Forge Developer portal.
  • A Node.js web server (such as Express) for 3-legged authentication.

Installation

    npm install forge-apis --save

Tutorial

Follow this tutorial to see a step-by-step authentication guide, and examples of how to use the Forge APIs.

Create an App

Create an app on the Forge Developer portal. Note the client ID and client secret.

Authentication

This SDK comes with an OAuth 2.0 client that allows you to retrieve 2-legged and 3-legged tokens. It also enables you to refresh 3-legged tokens. The tutorial uses 2-legged and 3-legged tokens for calling different Data Management endpoints.

2-Legged Token

This type of token is given directly to the application.

To get a 2-legged token run the following code. Note that you need to replace your-client-id and your-client-secret with your app's client ID and client secret.

var ForgeSDK = require('forge-apis');
var APS_CLIENT_ID = '<your-client-id>' , APS_CLIENT_SECRET = '<your-client-secret>';

// Initialize the 2-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
// if you want the token to auto refresh
var autoRefresh = true; // or false

var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(APS_CLIENT_ID, APS_CLIENT_SECRET, [
    'data:read',
    'data:write'
], autoRefresh);

oAuth2TwoLegged.authenticate().then(function(credentials){
    // The `credentials` object contains an access_token that is being used to call the endpoints.
    // In addition, this object is applied globally on the oAuth2TwoLegged client that you should use when calling secure endpoints.
}, function(err){
    console.error(err);
});

3-Legged Token

Generate an Authentication URL

To ask for permissions from a user to retrieve an access token, you redirect the user to a consent page.

Replace your-client-id, your-client-secret, and your-redirect-url with your app's client ID, client secret, and redirect URL, and run the code to create a consent page URL.

Note that the redirect URL must match the pattern of the callback URL field of the app’s registration in the My Apps section. The pattern may include wildcards after the hostname, allowing different redirect URL values to be specified in different parts of your app.

var ForgeSDK = require('forge-apis');
var APS_CLIENT_ID = '<your-client-id>', APS_CLIENT_SECRET = '<your-client-secret>', REDIRECT_URL = '<your-redirect-url>';

// Initialize the 3-legged OAuth2 client, set specific scopes and optionally set the `autoRefresh` parameter to true
// if you want the token to auto refresh
var autoRefresh = true;
var oAuth2ThreeLegged = new ForgeSDK.AuthClientThreeLegged(APS_CLIENT_ID, APS_CLIENT_SECRET, REDIRECT_URL, [
    'data:read',
    'data:write'
], autoRefresh);

// Generate a URL page that asks for permissions for the specified scopes.
oAuth2ThreeLegged.generateAuthUrl();
Retrieve an Authorization Code

Once a user receives permissions on the consent page, Forge will redirect the page to the redirect URL you provided when you created the app. An authorization code is returned in the query string.

GET /callback?code={authorizationCode}

Retrieve an Access Token

Request an access token using the authorization code you received, as shown below:

oAuth2ThreeLegged.getToken(authorizationCode).then(function (credentials) {
    // The `credentials` object contains an `access_token` and an optional `refresh_token` that you can use to call the endpoints.
}, function(err){
    console.error(err);
});

Note that access tokens expire after a short period of time. The expires_in field in the credentials object gives the validity of an access token in seconds. To refresh your access token, call the oAuth2ThreeLegged.refreshToken(credentials); method.

Example API Calls

Use the oauth2client (2-legged or 3-legged) object and the credentials object to call the Forge APIs.

// Import the library.
var ForgeSDK = require('forge-apis');

// Initialize the relevant clients; in this example, the Hubs and Buckets clients (part of the Data Management API).
var HubsApi = new ForgeSDK.HubsApi(); //Hubs Client
var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client

// Get the buckets owned by an application.
// Use the oAuth2TwoLegged client object and the credentials object that were
// obtained from the previous step
// notice that you need do add a bucket:read scope for the getBuckets to work
BucketsApi.getBuckets({}, oAuth2TwoLegged, credentials).then(function(buckets){
    console.log(buckets);
}, function(err){
     console.error(err);
});

// Get the hubs that are accessible for a member.
// Use the oAuth2ThreeLegged client object and the credentials object that were
// obtained from the previous step
HubsApi.getHubs({}, oAuth2ThreeLegged, credentials).then(function(hubs) {
    console.log(hubs);
}, function(err){
     console.error(err);
});

API Documentation

You can get the full documentation for the API on the Developer Portal

Documentation for API Endpoints

All URIs are relative to https://developer.api.autodesk.com/ (for example createBucket URI is 'https://developer.api.autodesk.com/oss/v2/buckets')

DerivativesApi regions

ForgeSDK.DerivativesApi(apiClient =null, region ='US'); // defaults to US
// if null/undefined, apiClient defaults to the default ForgeSDK.ApiClient.instance
Region Path
US /modelderivative/v2/
EMEA /modelderivative/v2/regions/eu/
EU /modelderivative/v2/regions/eu/

ex:

var DerivativesApi = new ForgeSDK.DerivativesApi(); // defaults to US
var DerivativesApi = new ForgeSDK.DerivativesApi(undefined, 'EMEA'); // Use EMEA endpoint
var DerivativesApi = new ForgeSDK.DerivativesApi(undefined, 'EU'); // Use EMEA endpoint
var DerivativesApi = new ForgeSDK.DerivativesApi(undefined, 'US'); // Use US endpoint

Classes

Class Method HTTP request Description
ForgeSdk.BucketsApi createBucket POST /oss/v2/buckets
ForgeSdk.BucketsApi deleteBucket DELETE /oss/v2/buckets/{bucketKey}
ForgeSdk.BucketsApi getBucketDetails GET /oss/v2/buckets/{bucketKey}/details
ForgeSdk.BucketsApi getBuckets GET /oss/v2/buckets
ForgeSdk.DerivativesApi getFormats GET /modelderivative/v2/designdata/formats
ForgeSdk.DerivativesApi translate POST /modelderivative/v2/designdata/job
ForgeSdk.DerivativesApi setReferences POST /modelderivative/v2/designdata/{urn}/references
ForgeSdk.DerivativesApi getThumbnail GET /modelderivative/v2/designdata/{urn}/thumbnail
ForgeSdk.DerivativesApi getManifest GET /modelderivative/v2/designdata/{urn}/manifest
ForgeSdk.DerivativesApi deleteManifest DELETE /modelderivative/v2/designdata/{urn}/manifest
ForgeSdk.DerivativesApi getDerivativeManifest GET /modelderivative/v2/designdata/{urn}/manifest/{derivativeUrn}
ForgeSdk.DerivativesApi getDerivativeManifestInfo HEAD /modelderivative/v2/designdata/{urn}/manifest/{derivativeUrn}
ForgeSdk.DerivativesApi getDerivativeDownloadUrl GET /modelderivative/v2/designdata/{urn}/manifest/{derivativeUrn}/signedcookies
ForgeSdk.DerivativesApi getMetadata GET /modelderivative/v2/designdata/{urn}/metadata
ForgeSdk.DerivativesApi getModelviewMetadata GET /modelderivative/v2/designdata/{urn}/metadata/{guid}
ForgeSdk.DerivativesApi getModelviewProperties GET /modelderivative/v2/designdata/{urn}/metadata/{guid}/properties
ForgeSdk.FoldersApi getFolder GET /data/v1/projects/{project_id}/folders/{folder_id}
ForgeSdk.FoldersApi getFolderContents GET /data/v1/projects/{project_id}/folders/{folder_id}/contents
ForgeSdk.FoldersApi getFolderParent GET /data/v1/projects/{project_id}/folders/{folder_id}/parent
ForgeSdk.FoldersApi getFolderRefs GET /data/v1/projects/{project_id}/folders/{folder_id}/refs
ForgeSdk.FoldersApi getFolderRelationshipsRefs GET /data/v1/projects/{project_id}/folders/{folder_id}/relationships/refs
ForgeSdk.FoldersApi postFolder POST /data/v1/projects/{project_id}/folders
ForgeSdk.FoldersApi postFolderRelationshipsRef POST /data/v1/projects/{project_id}/folders/{folder_id}/relationships/refs
ForgeSdk.HubsApi getHub GET /project/v1/hubs/{hub_id}
ForgeSdk.HubsApi getHubs GET /project/v1/hubs
ForgeSdk.ItemsApi getItem GET /data/v1/projects/{project_id}/items/{item_id}
ForgeSdk.ItemsApi getItemParentFolder GET /data/v1/projects/{project_id}/items/{item_id}/parent
ForgeSdk.ItemsApi getItemRefs GET /data/v1/projects/{project_id}/items/{item_id}/refs
ForgeSdk.ItemsApi getItemRelationshipsRefs GET /data/v1/projects/{project_id}/items/{item_id}/relationships/refs
ForgeSdk.ItemsApi getItemTip GET /data/v1/projects/{project_id}/items/{item_id}/tip
ForgeSdk.ItemsApi getItemVersions GET /data/v1/projects/{project_id}/items/{item_id}/versions
ForgeSdk.ItemsApi postItem POST /data/v1/projects/{project_id}/items
ForgeSdk.ItemsApi postItemRelationshipsRef POST /data/v1/projects/{project_id}/items/{item_id}/relationships/refs
ForgeSdk.ObjectsApi copyTo PUT /oss/v2/buckets/{bucketKey}/objects/{objectName}/copyto/{newObjName}
ForgeSdk.ObjectsApi createSignedResource POST /oss/v2/buckets/{bucketKey}/objects/{objectName}/signed
ForgeSdk.ObjectsApi deleteObject DELETE /oss/v2/buckets/{bucketKey}/objects/{objectName}
ForgeSdk.ObjectsApi deleteSignedResource DELETE /oss/v2/signedresources/{id}
ForgeSdk.ObjectsApi getObject GET /oss/v2/buckets/{bucketKey}/objects/{objectName}
ForgeSdk.ObjectsApi getObjectDetails GET /oss/v2/buckets/{bucketKey}/objects/{objectName}/details
ForgeSdk.ObjectsApi getObjects GET /oss/v2/buckets/{bucketKey}/objects
ForgeSdk.ObjectsApi getSignedResource GET /oss/v2/signedresources/{id}
ForgeSdk.ObjectsApi getStatusBySessionId GET /oss/v2/buckets/{bucketKey}/objects/{objectName}/status/{sessionId}
ForgeSdk.ObjectsApi uploadChunk PUT /oss/v2/buckets/{bucketKey}/objects/{objectName}/resumable
ForgeSdk.ObjectsApi uploadObject PUT /oss/v2/buckets/{bucketKey}/objects/{objectName}
ForgeSdk.ObjectsApi uploadSignedResource PUT /oss/v2/signedresources/{id}
ForgeSdk.ObjectsApi uploadSignedResourcesChunk PUT /oss/v2/signedresources/{id}/resumable
ForgeSdk.ProjectsApi getHubProjects GET /project/v1/hubs/{hub_id}/projects
ForgeSdk.ProjectsApi getProject GET /project/v1/hubs/{hub_id}/projects/{project_id}
ForgeSdk.ProjectsApi getProjectHub GET /project/v1/hubs/{hub_id}/projects/{project_id}/hub
ForgeSdk.ProjectsApi getProjectTopFolders GET /project/v1/hubs/{hub_id}/projects/{project_id}/topFolders
ForgeSdk.ProjectsApi postStorage POST /data/v1/projects/{project_id}/storage
ForgeSdk.UserProfileApi getUserProfile GET /userprofile/v1/users/@me Returns the profile information of an authorizing end user.
ForgeSdk.VersionsApi getVersion GET /data/v1/projects/{project_id}/versions/{version_id}
ForgeSdk.VersionsApi getVersionItem GET /data/v1/projects/{project_id}/versions/{version_id}/item
ForgeSdk.VersionsApi getVersionRefs GET /data/v1/projects/{project_id}/versions/{version_id}/refs
ForgeSdk.VersionsApi getVersionRelationshipsRefs GET /data/v1/projects/{project_id}/versions/{version_id}/relationships/refs
ForgeSdk.VersionsApi postVersion POST /data/v1/projects/{project_id}/versions
ForgeSdk.VersionsApi postVersionRelationshipsRef POST /data/v1/projects/{project_id}/versions/{version_id}/relationships/refs

Thumbnail

thumbnail

Support

[email protected]

forge-api-nodejs-client's People

Contributors

adamenagy avatar adskjohn avatar alexpiro avatar andrea-lisa avatar andreperegrina avatar arrotech avatar augustogoncalves avatar avrahamasher avatar clowenhg avatar cyrillef avatar dependabot[bot] avatar dmh126 avatar dukedhx avatar feelgood-interface avatar grantkellyadsk avatar gregra81 avatar jaylimboonkiat avatar kimekeunkyung avatar liskaj avatar reediculous456 avatar softremake avatar spark-developer avatar woweh avatar zivsher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

forge-api-nodejs-client's Issues

ObjectsApi.uploadObject set x-ads-content-sha1 header

Hi all,
I think that there is no way to set the x-ads-content-sha1 header using this wrapper.
You can pass the If-Match parameter, but according to API documentation they are different

If-Match | When overwriting an object, use the latest SHA-1 hash to verify that you are overwriting the latest data.A SHA-1 hash is returned every time you upload or overwrite an object. If the SHA-1 hash in the header does not match the current SHA-1 hash stored for this object in OSS, the request fails (status code 412).

x-ads-content-sha1 | A SHA-1 checksum of the object represented as a hexadecimal string.If the SHA-1 hash in the header does not match the SHA-1 hash computed by the server for the uploaded object, the request fails (status code 400).

Thanks.

Test are failing

Im trying to run the test, most of the are succesfull but theres 4 of them that are failing
image

Can you guys help me fixing the test or point me in the right direction to run them succesfully

Thanks

@gregra81

Can't get the API functions to work

I'm getting many 'x' is not a function when trying to invoke the functions listed in the API docs here:

This is the file I used to test this:

var ForgeSDK = require('forge-apis');
var CLIENT_ID = 'myid...' , CLIENT_SECRET = 'mysecret...', REDIRECT_URL = 'http://localhost:3000';
var autoRefresh = true;
var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(CLIENT_ID, CLIENT_SECRET, [
    'data:read',
    'data:write'
], autoRefresh);

var oAuth2ThreeLegged = new ForgeSDK.AuthClientThreeLegged(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, [
    'data:read',
    'data:write'
], autoRefresh);

var str2leg = 'saved credentials string';
var str3leg = 'other saved credentials string';

var TwoLeggedCredentials = JSON.parse(str2leg);
var ThreeLeggedCredentials = JSON.parse(str3leg);

console.log(ForgeSDK.BucketsApi.getBuckets(oAuth2TwoLegged, TwoLeggedCredentials));

And I got that getBuckets is not a function.

Then I tried to load that same file to a node shell and run the following commands to test more functions, nothing seemed to work.
I couldn't find any of the functions listed in the docs when I tried to explore the ForgeSDK object...

> console.log(Object.getOwnPropertyNames(ForgeSDK.Buckets));
[ 'length', 'name', 'prototype', 'constructFromObject' ]
undefined
> var x = new ForgeSDK.Buckets
undefined
> console.log(x);
exports { items: undefined, next: undefined }
undefined
> console.log(Object.getOwnPropertyNames(x));
[ 'items', 'next' ]
undefined
> console.log(Object.getOwnPropertyNames(x.items));
TypeError: Cannot convert undefined or null to object
> console.log(ForgeSDK.Buckets);
{ [Function: exports] constructFromObject: [Function: constructFromObject] }
undefined
> console.log(ForgeSDK.Buckets.items);
undefined
> ForgeSDK.AppPackagesApi.getUploadUrl()
TypeError: ForgeSDK.AppPackagesApi.getUploadUrl is not a function

I'm probably not doing it right, can you please give an example on how to use the api functions?

PS: of course I use the right id, secret and credentials.

Oder by version should be implemented or fixed

Hello,

As we are using this API on our project when you call :

ForgeSdk.ItemsApi getItemVersions GET /data/v1/projects/{project_id}/items/{item_id}/versions

This function isn't ordering correctly as you can see below (v10 and v11 are above v1).

image

Best regards

promise not compatible to async/await

Hello,

The promise return seem to not be compatible with async/await.

Here is my code :

var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(secret.clientId, secret.clientSecret, forgeScope, true);
await oAuth2TwoLegged.authenticate();

// other code here

The proccess is finish without any error and without any response.
The rest of the code is not excecuted.

autoRefresh example?

Can you show a concrete example using autoRefresh = true? Do my client code needs to pass a callback or can I assume calling OAuth2TwoLegged.prototype.getCredentials will always return a valid token? By looking at the implementation it seems to me autoRefresh is not doing anything ...

Type Definition

I read #34.
It said it's working, but it's been a long time till now without any d.ts file or typescript rewrite.
As there has been no reply to the last question about progess, hereby I open a new issue.

Is there any specific plan?

DELETE verbs or urlencoded VERBS throws exception

if you use
ModelDerivative.deleteManifest (content.urn, forgeToken.RW, forgeToken.RW.getCredentials ())
or
ObjectsApi.deleteObject (bucket, desc.objectKey, forgeToken.RW, forgeToken.RW.getCredentials ())

you get an exception wth the following message
Error:TypeError: requestParams.form is not a function

https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/src/ApiClient.js#L342
< requestParams.form(this.normalizeParams(formParams));
should be

requestParams.form =this.normalizeParams(formParams);

Make its possible to set the basePath for staging.

For our staging environment, the basePath needs to be set to https://developer-stg.api.autodesk.com. I solve that now by doing something like:

    const apiClient = new ForgeSDK.ApiClient()
    apiClient.basePath = "https://developer-stg.api.autodesk.com"
    ...
    const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(...)
    oAuth2TwoLegged.basePath = "https://developer-stg.api.autodesk.com"

Is it possible to make this settable by providing the basePath to the constructor (options object), or something else?

Problem with HubsApi

Hi, I have a trouble with https://developer.api.autodesk.com/project/v1/hubs/project/v1/hubs
Right now I'm testing this endpoint in Postman with the following headers:

Content-Type: application/vnd.api+json
Accept: application/json, application/vnd.api+json
Authorization: Bearer {{AccessToken}}

Unfortunately, I've got an error with 403 status code, when sending this request:

{
"jsonapi": {
"version": "1.0"
},
"errors": [
{
"status": "403",
"code": "BIM360DM_ERROR",
"title": "Unable to get hubs from BIM360DM US.",
"detail": "You don't have permission to access this API"
},
{
"status": "403",
"code": "BIM360DM_ERROR",
"title": "Unable to get hubs from BIM360DM EMEA.",
"detail": "You don't have permission to access this API"
}
]
}

Other API calls ( https://developer.api.autodesk.com/modelderivative/v2/designdata/formats, for instance, are working properly)

What can be the reason for this?

Upload rvt keep failing statusCode: 401, statusMessage: 'Unauthorized'

Trying to upload an object

**** Uploading file. bucket:forge_sample_c6eaxriflqyzvmirmt306hsmawehv9ig filePath:D:/Project/bca-rvt/CCDC_HP_B4_ST_TYPICAL.rvt
D:/Project/bca-rvt/CCDC_HP_B4_ST_TYPICAL.rvt
buckets > [object Object]
{ statusCode: 401, statusMessage: 'Unauthorized' }
**** Upload file response: undefined

fs.createReadStream(filePath).pipe(`
request.put({
url:'https://developer.api.autodesk.com/oss/v2/buckets/'+bucketKey+'/objects/'+fileName,
headers:{
'Authorization':' Bearer ' + oAuth2TwoLegged.access_token
}

        },function(err,response,body){
          if(err) {
            reject(null);
          }
          resolve(body);
        }));

Refresh tokens problems

Hi,

I'm trying to use oAuth2ThreeLegged.refreshToken and oAuth2TwoLegged.refreshToken to refresh the tokens but there seems to be problems with that.

oAuth2TwoLegged doesn't even find a refreshToken function.

And oAuth2ThreeLegged manages to refresh once, but afterwards I get:

(node:5936) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): [object Object]

Is there a limit on update requests per minute? If so how long should I wait before updating?

getObject returns empty body

after switching from request to superagent in 0.9.0 release getObject stopped working, the response.body is empty ({}), no any errors.
Most likely it affects only objects larger than a certain size (our models are usually bigger than 500K).
Anyway, the solution is to buffer the response. I've made a PR #82
Please review and accept.

Header parameters are not appended to `ApiClient.callApi`

Hi,
I'm currently implementing the partial uploads of large files to the Forge platform, and encountered an issue which gives { statusCode: 400, statusMessage: 'Bad Request' }. Digged the codebase and found that header parameters that are prepared in ObjectsApi.uploadChunk:

 var headerParams = {
        'Content-Length': contentLength,
        'Content-Range': contentRange,
        'Content-Disposition': opts['contentDisposition'],
        'If-Match': opts['ifMatch'],
        'Session-Id': sessionId
      };

are sent to ApiClient.callApi, but those parameters are not actually added at all to the request, hence causing issues.

Can you please clarify this?

ApiClient.convertToType is not a function

Hi,

Updated the SDK to the latest revision, now no longer able to submit a job for translation.
it gives an error when building a job object for translation function call:

    job = new ForgeAPI.JobPayload { 
        input: {
            urn: urn
       },
        output: {
            formats: [ {type: "svf", views: ["2d","3d"]} ]
        }
   }

JobPayload is using JobPayloadInput and JobPayloadOutput which use a method called ApiClient.convertToType that no longer exists.

Can you please advice what to do?

`FoldersApi.postFolder` is missing pathParameter for `project_id`

Hi dear team,

The postFolder method of FoldersApi does not have a proper definition for pathParams which should include project_id.
https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/src/api/FoldersApi.js#L329 should be something like this:

var pathParams = { project_id: body.projectID };

Also the documentation for:
https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/CreateFolder.md
...is missing.

Commands API check permission using wrong request method

When using checkPermission method on Commands API class, regardless of the input it always returns status code 404:

{
  "developerMessage": "The requested resource does not exist.",
  "moreInfo": "https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/",
  "errorCode": "org.mozilla.javascript.Undefined@0"
}

It seems like the internal method _commandsApiCal is using the request method GET and according to the documentation it should be POST

return this.apiClient.callApi(
'/data/v1/projects/{project_id}/commands', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, returnType, oauth2client, credentials
);

Documentation here:
https://forge.autodesk.com/en/docs/data/v2/reference/http/CheckPermission/

I can successfully use the check permission command when calling the API externally.

Best Regards,
/Karl

Tutorial for Forge API for NestJS

NestJS is getting more and more popular. Although there is a DefinitelyType of forge api, it would be better if AutoDesk could provide a proper port from ExpressJS to NestJS.

Planning for Direct-to-S3 approach

Hello - recently it was announced that certain data management API calls would be deprecated in favor of direct uploads and downloads from the underlying AWS S3 bucket. We make use of a couple of methods in the ObjectsApi and I'm wondering if we'll need to plan for these changes or if this package will be handling that automatically.

For example, we use ObjectsApi.uploadChunk for resumable uploads, which calls this soon-to-be-deprecated method. Will uploadChunk be updated under the hood to call the new direct-to-s3 endpoint?

Obtaining room/area information from forge api

Hi
I need is to get room/area objects with the hierarchy of linked objects from the revit model. Right now I am using this project as a start point. Unfortunately, the room information in lost. As far as I understand, it is removed during the translation process. There are some workarounds like this one, but it doesn't seem to work for our case. Is there any straightforward way to retrieve room information from rvt in Forge?

getBuckets syntax

1-) getBuckets doesn't work without a callback function(err). So, I suggest to add this callback to the sample.
2-) getBuckets need "buckets: read". The sample on this page suggest to use the "token that were obtained from the previous step". I suggest to add a comment "notice that you need do add a buckets: read permission"

isuues with error handling

  1. Errors should be instance of Error, currently its a plain objects
  2. details of is error is skipped. For example error for createBucket request sya only 400:badRequest
    but in response body detailed description is available about allowed characters

cors error on AuthClientTwoLegged

Hi, i was trying the api's in one of my angular app, i was using 2 legged authentication and i end up with cors error, is there any other config i need to do before i try these api.

Failed to load https://developer.api.autodesk.com/authentication/v1/authenticate: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://seligentinfra.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Thanks

DerivativesApi.getDerivativeManifest() always returns a 400

Looks like there's something wrong with the getDerivativeManifest() function. When I use it like this:

                DerivativesApi.getDerivativeManifest(designUrn, derivUrn, {}, oAuth2TwoLegged, credentials)
                .then(function(done){
                    console.log(done);
                })
                .catch(function(err){
                    console.log(err);
                })

I always get this:

{ statusCode: 400, statusMessage: 'Bad Request' }

But when I instead log out my access token and urn's into a formatted curl request, that curl request works just fine:

console.log("curl -X 'GET'  -H 'Authorization: Bearer "+credentials.access_token+"' -v 'https://developer.api.autodesk.com/modelderivative/v2/designdata/"+designUrn+"/manifest/"+derivUrn+"'");

That gives me a curl command that I can just run (**'d out some sensitive parts):

$ curl -X 'GET'  -H 'Authorization: Bearer v6MLmO8mIc8UPI*************' -v 'https://developer.api.autodesk.com/modelderivative/v2/designdata/dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6aW5zdHJ1Y3RhYmxlcy1mb3JnZS1kZXYt*********/manifest/urn%3Aadsk.viewing%3Afs.file%3AdX**************JnZS1kZXYtYnVja2V0L3Rlc3Quc3Rs%2Foutput%2F1%2Ftest.svf.png01_thumb_100x100.png'

... and it spits out data:

?PNG

IHDRdp?Td??IDATx^?]il]?u??7?O\?MK?TY?#5??ڍ׵]'?? u??hS(? E?(Z???ڢ@k???hDZ?cɑ?X?eS?(??HJ?׷?g???3?Σ???A?{gΜ????v/C/??5??"????w?չ??Q????Z??ޫ?
                                                                                                                                        BGo?~J?????g"??Q?ՠ?&????R?}tJQS1???I[t???tKQ*8

Just FYI, there's a bug that deserves a failing unit test.

[Feature Request] Add TypeScript definitions

Hello Forge-Team,

I'd like to ask you to add TypeScript definitions for the NodeJS client.

For us, TypeScript is crucial in our big projects, and as we want to make heavy use of Forge, we'd highly appreciate having TypeScript definitions for your API.

Regards,
Michael

ItemsAPI.postItem Generates 400 Error

Howdy all,

Software team lead for Bechtel Center at Purdue here.

Problem: I was getting a "BAD_INPUT" error by utilizing the postItem() function.

Description: Consulted the api docs, and found this note on the data.attributes.displayName field:

Note that for A360 projects, this field is required.

Note that for BIM 360 projects, this field is reserved for future releases and should not be used. Use included[0].attributes.name for the file name.

The current version of postItem function utilizes the "CreateStorageDataAttributes" model within a "createItemData". A TypeScript compile error results from using "displayName" instead of "name" with this model, but using "name" results in a 400 error as shown below (1). By implementing a workaround and modifying by types file I could get it working (2).

It is quite possible I missed something, and I simply used something incorrectly.

Thank you for your work on this module, have a great day.

Supporting Docs:
1:

API ERROR CODE:  400
MESSAGE:  BadRequest
BODY:  {
  jsonapi: { version: '1.0' },
  errors: [
    {
      id: REDACTED,
      status: '400',
      code: 'BAD_INPUT',
      title: 'One or more input values in the request were bad',
      detail: 'Display name not found, should be in resource: "data.attributes.displayName".'
    }
  ]
}

2:

CODE:  201
BODY:  {
  jsonapi: { version: '1.0' },
  links: {
    self: {
      href: REDACTED
    }
  },
  data: {
    type: 'items',
    id: REDACTED,
    attributes: {
      displayName: 'foo.txt',
      createTime: '2022-01-27T19:55:39.0000000Z',
      createUserId: REDACTED,
      createUserName: 'Gavin',
      lastModifiedTime: '2022-01-27T19:55:39.0000000Z',
      lastModifiedUserId: REDACTED,
      lastModifiedUserName: 'Gavin',
      hidden: false,
      reserved: false,
      extension: [Object]
    },
    links: { self: [Object] },
    relationships: {
      tip: [Object],
      versions: [Object],
      parent: [Object],
      refs: [Object],
      links: [Object]
    }
  },
  included: [
    {
      type: 'versions',
      id: REDACTED,
      attributes: [Object],
      links: [Object],
      relationships: [Object]
    }
  ]
}

inconsistent range naming

Forge docs says 'Range'
the node-js client use 'range'

to keep backward compatibility, we could use:
var headerParams = {
'Range': opts['range'] || opts['Range'],

ObjectsApi.js line #283, #430

"The limit value is invalid." error

I'm trying to use GetFolderContents api as per below (in C#):
var folderItems = foldersApi.GetFolderContents(projectId, folderId, filterType: new List<string>() { "items" }, pageLimit: 1000);

but I'm getting below error:
Error calling GetFolderContents: { "jsonapi": { "version": "1.0" }, "errors": [{ "id": "6ffd7c96-0c44-4223-8fa2-713bd02a548a", "status": "400", "code": "BAD_INPUT", "title": "One or more input values in the request were bad", "detail": "The limit value is invalid." } ] }

I am using v1.5 of the Forge dll from nuget btw

Example on landing page fails

Hi there,

Just a heads up that there's a somewhat offputting moment in the (would be) very helpful example on the main readme page for this repo: the required scopes for the example are not in place. Further, the example fails silently. In order to see the error at all, I had to take the access token, log it, then do the getBuckets request via curl in order to see this:

Token does not have the privilege for this request.

That made it clear that I needed to find a page about scopes, which turned out to be this one:

https://developer.autodesk.com/en/docs/oauth/v2/overview/scopes/

So I could then figure out to add 'bucket:read' to this:

var oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(CLIENT_ID, CLIENT_SECRET, [
    'data:read',
    'data:write'
], autoRefresh);

Updating the docs would be very much appreciated by future devs, I'm sure. Thanks!

Where to "run the following code"

It says in the readme to "run the following code" for the 2-legged and 3-legged tokens, but where this code is supposed to be placed?
I couldn't even find in any of the files 'CLIENT_ID'.

Edit:
So I placed the 2/3-legged code in a file and ran it with node, in the 3-legged oAuth2ThreeLegged.generateAuthUrl(); doesn't return authorizationCode in the url, and if I try to navigate to that url, I get:

{"developerMessage":"The required parameter(s) redirect_uri not present in the request","userMessage":"","errorCode":"AUTH-008","more info":"http://developer.api.autodesk.com/documentation/v1/errors/AUTH-008"}

Upload of JSON file using ForgeSDK, ObjectsAPI to Forge bucket failing

I'm trying to take a set of file stored in one bucket and copy them to another (one is transient and one is temporary - the files are to be stored for a longer period of time). I'm using the NodeJS ForgeSDK, using getObject to download the file, then uploadObject to put it in the second bucket. This seems to work fine for most of the files I'm moving, but fails when I try to use it on a JSON file.

I've tried converting the JSON both to a buffer and to a string before the uploadObject call, both fail giving a gateway timeout error.

ApiClient Default Headers

Hey,

I'm trying to add custom headers to requests made to forge API. I noticed that the ApiClient attribute defaultHeaders is not being used within the api client, meaning even if we create a custom client with required headers, they never get applied to the requests made against forge API. I'd guess this was a bug with SwaggerCode gen.

Any chance the ApiClient could be modified to actually apply the default headers that are set?

I.e. normally swagger autogen would generate this line: request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));

However in the ApiClient here, the default headers are never actually applied.

I'd make a PR but I'd assume regen through swagger would be approved approach...

Tom

Non white space encoded characters in generateAuthUrl() generated URL

The following code will produce non white space encoded characters

var scope =[ 'data:read', 'data:write', 'data:create', 'data:search', 'account:read', 'user-profile:read', 'viewables:read' ] ;
var oauth =new ForgeSDK.AuthClientThreeLegged (client_id, client_secret, redirect_uri, scope, false) ;
console.log (oauth.generateAuthUrl ()) ;

https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=XXX&redirect_uri=http://localhost:3000/callback&scope=data:read data:write data:create data:search account:read user-profile:read viewables:read&state=undefined

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.