### Start the REPL Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/try-it-in-command-line.md Command to start the SDK's command-line REPL. ```bash $ yarn run repl ``` -------------------------------- ### File Store Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/token-store.md Example of how to initialize the SDK with the file token store. ```javascript const clientId = ""; const clientSecret = "" const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId, clientSecret, tokenStore: sharetribeIntegrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### Memory Store Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/token-store.md Example of how to initialize the SDK with the memory token store. ```javascript const clientId = ""; const clientSecret = "" const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId, clientSecret, tokenStore: sharetribeIntegrationSdk.tokenStore.memoryStore() }); ``` -------------------------------- ### Install dependencies Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Installs the necessary dependencies for SDK development. ```shell $ yarn install ``` -------------------------------- ### Full example of Github release draft Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md A complete example of the content for a Github release draft. ```markdown **Tag version:** v1.2.3 **Release title:** v1.2.3 **Describe this release:** ```markdown ### Added - Added many things ### Changed - Changed this and that ``` ``` -------------------------------- ### files.query Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/06-images-files-attachments.md Example of querying files with pagination. ```javascript integrationSdk.files.query({ perPage: 20, page: 1 }) .then(res => { res.data.forEach(file => { console.log('File:', file.attributes.name); }); }) .catch(err => { console.error('Query failed:', err.status); }); ``` -------------------------------- ### Command method options example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/calling-the-api.md Example of using the onUploadProgress option for command methods. ```javascript const logProgress = (progressEvent) => { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(percentCompleted + '% completed'); } integrationSdk.images.upload({ image: file }, {}, { onUploadProgress: logProgress }) ``` -------------------------------- ### Installation Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/README.md Install the SDK using Yarn. ```sh yarn add sharetribe-flex-integration-sdk ``` -------------------------------- ### File Token Store Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/10-utilities.md Example of creating an SDK instance with a file-based token store using `tokenStore.fileStore()`. ```typescript tokenStore.fileStore(): TokenStore ``` ```javascript const sdk = integrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', tokenStore: integrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### Complete Initialization Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md A comprehensive example demonstrating the initialization of the Sharetribe Flex Integration SDK with various configuration options including authentication, storage, rate limiting, custom types, and HTTP agents. ```javascript const integrationSdk = require('sharetribe-flex-integration-sdk'); const sdk = integrationSdk.createInstance({ // Authentication clientId: 'your-client-id', clientSecret: 'your-client-secret', // Storage tokenStore: integrationSdk.tokenStore.fileStore(), // Rate Limiting (recommended for production) queryLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodQueryLimiterConfig ), commandLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodCommandLimiterConfig ), // Custom Types typeHandlers: [ { sdkType: integrationSdk.types.UUID, appType: MyUUID, writer: (v) => new integrationSdk.types.UUID(v.myUuid), reader: (v) => new MyUUID(v.uuid) } ], // HTTP Configuration httpAgent: new require('http').Agent({ keepAlive: true, maxSockets: 10 }), httpsAgent: new require('https').Agent({ keepAlive: true, maxSockets: 10 }), // API Configuration baseUrl: 'https://flex-integ-api.sharetribe.com', version: 'v1', // Debug Mode transitVerbose: false }); ``` -------------------------------- ### Memory Token Store Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/10-utilities.md Example of creating an SDK instance with an in-memory token store using `tokenStore.memoryStore()`. ```typescript tokenStore.memoryStore(): TokenStore ``` ```javascript const sdk = integrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', tokenStore: integrationSdk.tokenStore.memoryStore() }); ``` -------------------------------- ### Rate Limiter Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/10-utilities.md Example of creating an SDK instance with a custom rate limiter using `createRateLimiter` and `prodCommandLimiterConfig`. ```javascript const sdk = integrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', commandLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodCommandLimiterConfig ) }); ``` -------------------------------- ### GET /marketplace/show Response Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON response for retrieving marketplace information. ```json { "data": { "id": {"uuid": "..."}, "type": "marketplace", "attributes": { "name": "Marketplace Name", "description": "Description", "..." } } } ``` -------------------------------- ### Fetch Marketplace Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/02-marketplace.md Example of how to fetch marketplace information using the integration SDK. ```javascript integrationSdk.marketplace.show() .then(res => { console.log('Marketplace:', res.data.attributes.name); }) .catch(err => { console.error('Failed to fetch marketplace:', err.status, err.statusText); }); ``` -------------------------------- ### GET /users/show Response Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON response for retrieving a specific user. ```json { "data": { "id": {"uuid": "..."}, "type": "user", "attributes": { "email": "user@example.com", "firstName": "John", "lastName": "Doe", "..." } } } ``` -------------------------------- ### Approve Listing Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/04-listings.md Example of how to approve a listing using the integration SDK. ```javascript const { UUID } = integrationSdk.types; integrationSdk.listings.approve({ id: new UUID('listing-uuid-here') }) .then(res => { console.log('Listing approved'); }) .catch(err => { console.error('Approval failed:', err.status); }); ``` -------------------------------- ### Query method example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/calling-the-api.md Example of calling a query method with query parameters. ```javascript integrationSdk.listings.query({perPage: 5}) // Calls GET /integration_api/listings/query?perPage=5 ``` -------------------------------- ### Command method example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/calling-the-api.md Example of calling a command method with body parameters, query parameters, and options. ```javascript integrationSdk.listings.update({ id: new UUID("e3dab126-8280-4f02-b9d6-f217ce406878"), title: 'New title', price: new Money(5000, 'USD') }, {expand: true}); // Calls POST /integration_api/listings/update?expand=true // with id, title and price serialized in the request body ``` -------------------------------- ### GET /users/query Response Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON response for querying users with filters and pagination. ```json { "data": [ { "id": {"uuid": "..."}, "type": "user", "attributes": {...} } ], "meta": { "totalItems": 100, "totalPages": 5, "page": 1, "perPage": 20 } } ``` -------------------------------- ### Open Listing Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/04-listings.md Example of how to open a closed listing using the integration SDK. ```javascript const { UUID } = integrationSdk.types; integrationSdk.listings.open({ id: new UUID('listing-uuid-here') }) .then(res => { console.log('Listing opened'); }) .catch(err => { console.error('Open failed:', err.status); }); ``` -------------------------------- ### Basic Initialization Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/01-sdk-initialization.md Example of basic SDK initialization with client ID and client secret. ```javascript const sharetribeIntegrationSdk = require('sharetribe-flex-integration-sdk'); const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret' }); ``` -------------------------------- ### Draft new release on Github Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Example content for drafting a new release on Github. ```markdown **Tag version:** **Release title:** **Describe this release:** ```markdown ``` ``` -------------------------------- ### Path to Function Translation Examples Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md Examples demonstrating how URL paths are converted to SDK method names using camelCase transformation. ```text listings/show → sdk.listings.show() users/update_profile → sdk.users.updateProfile() transactions/transition_speculative → sdk.transactions.transitionSpeculative() availability_exceptions/query → sdk.availabilityExceptions.query() ``` -------------------------------- ### Money Usage Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Demonstrates how to create and use Money instances for different currencies. ```javascript const { Money } = integrationSdk.types; const price = new Money(5000, 'USD'); // $50.00 const priceEur = new Money(150, 'EUR'); // €1.50 const priceJpy = new Money(2500, 'JPY'); // ¥2500 integrationSdk.listings.create({ title: 'Item', price: price }) ``` -------------------------------- ### Example: Monitoring Upload Progress Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md Shows how to use the `onUploadProgress` option within per-request options to track the progress of file uploads. ```javascript integrationSdk.images.upload( { image: fileBuffer }, {}, { onUploadProgress: (progressEvent) => { const percentComplete = (progressEvent.loaded / progressEvent.total) * 100; console.log(`Upload ${percentComplete}% complete`); } } ); ``` -------------------------------- ### Example: Custom UUID Type Handler Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md Provides an example of implementing a custom `TypeHandler` for a UUID, demonstrating the `writer` and `reader` functions. ```javascript class MyUUID { constructor(value) { this.myUuid = value; } } const handler = { sdkType: integrationSdk.types.UUID, appType: MyUUID, writer: (appValue) => new integrationSdk.types.UUID(appValue.myUuid), reader: (sdkValue) => new MyUUID(sdkValue.uuid) }; const sdk = createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', typeHandlers: [handler] }); ``` -------------------------------- ### images.upload Node.js Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/06-images-files-attachments.md Example of uploading an image using a Node.js Buffer. ```javascript const fs = require('fs'); const imageBuffer = fs.readFileSync('/path/to/image.jpg'); integrationSdk.images.upload({ image: imageBuffer }, {}, { onUploadProgress: (progressEvent) => { console.log('Upload progress:', progressEvent.loaded / progressEvent.total); } }) .then(res => { console.log('Image uploaded:', res.data.id); }) .catch(err => { console.error('Upload failed:', err.status); }); ``` -------------------------------- ### Close Listing Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/04-listings.md Example of how to close a listing using the integration SDK. ```javascript const { UUID } = integrationSdk.types; integrationSdk.listings.close({ id: new UUID('listing-uuid-here') }) .then(res => { console.log('Listing closed'); }) .catch(err => { console.error('Close failed:', err.status); }); ``` -------------------------------- ### Promise handling example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/calling-the-api.md Example of handling the Promise returned by SDK methods for success and error responses. ```javascript const promise = integrationSdk.listings.query(); // Handle success response promise.then(response => { console.log(response)} ); // Handle error response promise.catch(response => { console.log(response)} ); ``` -------------------------------- ### Initialization with File-Based Token Storage Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/01-sdk-initialization.md Example of SDK initialization using file-based token storage. ```javascript const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', tokenStore: sharetribeIntegrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### fileStore Usage Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md Example of how to use the persistent file-based token store. ```typescript tokenStore.fileStore(): TokenStore ``` ```javascript const sdk = createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', tokenStore: integrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### memoryStore Usage Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md Example of how to use the in-memory token store. ```typescript tokenStore.memoryStore(): TokenStore ``` ```javascript const sdk = createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', tokenStore: integrationSdk.tokenStore.memoryStore() }); ``` -------------------------------- ### UUID Usage Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Demonstrates how to create and use a UUID instance with the SDK. ```javascript const { UUID } = integrationSdk.types; const listingId = new UUID('550e8400-e29b-41d4-a716-446655440000'); integrationSdk.listings.show({ id: listingId }) ``` -------------------------------- ### Initialization with Rate Limiters Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/01-sdk-initialization.md Example of SDK initialization with custom rate limiters for queries and commands. ```javascript const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', queryLimiter: sharetribeIntegrationSdk.util.createRateLimiter( sharetribeIntegrationSdk.util.devQueryLimiterConfig ), commandLimiter: sharetribeIntegrationSdk.util.createRateLimiter( sharetribeIntegrationSdk.util.devCommandLimiterConfig ) }); ``` -------------------------------- ### POST /listings/create Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for creating a new listing. ```json { "title": "Listing Title", "description": "Listing description", "price": {"amount": 5000, "currency": "USD"}, "location": {"lat": 40.7128, "lng": -74.0060}, "..." } ``` -------------------------------- ### fileAttachments.query Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/06-images-files-attachments.md Example of querying file attachments filtered by source and sourceId. ```javascript const { UUID } = integrationSdk.types; integrationSdk.fileAttachments.query({ perPage: 10, source: 'message', sourceId: new UUID('message-uuid-here') }) .then(res => { res.data.forEach(attachment => { console.log('Attachment:', attachment.attributes); }); }) .catch(err => { console.error('Query failed:', err.status); }); ``` -------------------------------- ### images.upload Browser Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/06-images-files-attachments.md Example of uploading an image using a browser File object. ```javascript const fileInput = document.getElementById('imageInput'); const file = fileInput.files[0]; integrationSdk.images.upload({ image: file }) .then(res => { console.log('Image uploaded:', res.data.id); }) .catch(err => { console.error('Upload failed:', err.status); }); ``` -------------------------------- ### LatLng Usage Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Demonstrates how to create and use a LatLng instance for geographic coordinates. ```javascript const { LatLng } = integrationSdk.types; const location = new LatLng(40.7128, -74.0060); // New York City integrationSdk.listings.create({ title: 'Item in NYC', location: location }) ``` -------------------------------- ### JSON reviver example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Example showing how to use the `reviver` function to parse JSON strings containing SDK types. ```javascript const jsonString = '{\"_sdkType\":\"UUID\",\"uuid\":\"550e8400-e29b-41d4-a716-446655440000\"}'; const parsed = JSON.parse(jsonString, integrationSdk.types.reviver); // parsed is now a UUID instance ``` -------------------------------- ### BigDecimal Usage Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Demonstrates how to create a BigDecimal instance and suggests using a library like decimal.js for calculations. ```javascript const { BigDecimal } = integrationSdk.types; // Use string to avoid floating-point precision issues const preciseValue = new BigDecimal('123.456789'); // Recommended: use a library like decimal.js for calculations const Decimal = require('decimal.js'); const calculated = new Decimal(preciseValue.value); ``` -------------------------------- ### Adding Custom Interceptors Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md Example of how to add custom interceptors to the SDK at initialization. ```javascript class CustomInterceptor { enter(ctx) { // Process context return ctx; } } // Add to specific endpoints by modifying endpointDefinitions ``` -------------------------------- ### Example of serializing and deserializing with reviver and replacer Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/serializing-types-to-json.md This example demonstrates how to use `types.replacer` with `JSON.stringify` and `types.reviver` with `JSON.parse` to preserve type information, specifically for a `UUID` object. ```javascript const { reviver, replacer, UUID } = require('sharetribe-flex-sdk').types; const testData = { id: new UUID('f989541d-7e96-4c8a-b550-dff1eef25815') }; const roundtrip = JSON.parse(JSON.stringify(testData, replacer), reviver); assert(roundtrip.id.constructor.name === 'UUID'); ``` -------------------------------- ### Example: Handling common HTTP error status codes Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/errors.md An example demonstrating how to catch errors and handle specific HTTP status codes like 404, 401, and 429. ```javascript integrationSdk.listings.show({ id: new integrationSdk.types.UUID('invalid-id') }) .catch(err => { if (err.status === 404) { console.log('Listing not found'); } else if (err.status === 401) { console.log('Authentication failed'); } else if (err.status === 429) { console.log('Rate limit exceeded, wait before retrying'); } else { console.log(`Error: ${err.status} ${err.statusText}`); console.log('Details:', err.data); } }); ``` -------------------------------- ### User-Agent String Examples Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md Illustrates the User-Agent string constructed by the SDK for Node.js and browser environments. ```text sharetribe-flex-integration-sdk-js/1.13.0 (node/14.17.0) ``` ```text Mozilla/5.0... sharetribe-flex-integration-sdk-js/1.13.0 ``` -------------------------------- ### Example of object query parameters with utility Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/object-query-parameters.md Shows how to use the `sharetribeIntegrationSdk.util.objectQueryString` utility to simplify building object query parameters. ```javascript const sdkUtil = sharetribeIntegrationSdk.util; integrationSdk.listings.show({ id: listingId, include: ["images"], "fields.image": ["variants.my-variant"], "imageVariant.my-variant": sdkUtil.objectQueryString({ w: 640, h: 1280, fit: 'scale' }) }).then(res => { // res.data contains the response data }); ``` -------------------------------- ### LatLngBounds Usage Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Demonstrates how to create and use a LatLngBounds instance to define a geographic bounding box. ```javascript const { LatLng, LatLngBounds } = integrationSdk.types; const ne = new LatLng(40.8, -73.9); const sw = new LatLng(40.7, -74.1); const bounds = new LatLngBounds(ne, sw); ``` -------------------------------- ### Create a new listing Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/04-listings.md Example of creating a new listing with details such as title, description, price, and location. ```javascript const { UUID, Money, LatLng } = integrationSdk.types; integrationSdk.listings.create({ title: 'Mountain Bike', description: 'Used mountain bike in great condition', price: new Money(15000, 'USD'), location: new LatLng(40.7128, -74.0060) }) .then(res => { console.log('Listing created:', res.data.id); }) .catch(err => { console.error('Creation failed:', err.status); }); ``` -------------------------------- ### Rate Limiting Configuration Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Example of how to configure rate limiters for production using predefined configurations. ```javascript const sdk = integrationSdk.createInstance({ clientId: '...', clientSecret: '...', queryLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodQueryLimiterConfig ), commandLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodCommandLimiterConfig ) }); ``` -------------------------------- ### Image Upload Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/uploading-images.md Demonstrates how to upload an image using either a file path string or a file stream. ```javascript const fs = require('fs'); const sharetribeIntegrationSdk = require('sharetribe-flex-integration-sdk'); const clientId = ""; const clientSecret = "" const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId, clientSecret, }); // Using a string param integrationSdk.images.upload({image: '/path/to/file'}); // Using a file stream param const readStream = fs.createReadStream('/path/to/file'); integrationSdk.images.upload({image: readStream}) ``` -------------------------------- ### Create SDK Instance Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/try-it-in-command-line.md JavaScript code to create a new instance of the integration SDK with provided credentials. ```javascript const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId, clientSecret }); ``` -------------------------------- ### Example: Creating Query and Command Limiters Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/configuration.md Demonstrates how to create distinct rate limiters for queries and commands using the `createRateLimiter` function with specific configurations. ```javascript const queryLimiter = integrationSdk.util.createRateLimiter({ bucketInitial: 10, bucketIncreaseInterval: 1000, bucketIncreaseAmount: 1, bucketMaximum: 100 }); const commandLimiter = integrationSdk.util.createRateLimiter({ bucketInitial: 5, bucketIncreaseInterval: 2000, bucketIncreaseAmount: 1, bucketMaximum: 50 }); const sdk = createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', queryLimiter, commandLimiter }); ``` -------------------------------- ### Converting types from other SDKs Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/types.md Example demonstrating how to convert a UUID from the Marketplace SDK to the Integration SDK's type. ```javascript // Converting types from other SDKs const marketplaceSDKUUID = marketplaceSDK.listings[0].id; const integrationSDKUUID = integrationSdk.types.toType(marketplaceSDKUUID); integrationSdk.listings.show({ id: integrationSDKUUID }) ``` -------------------------------- ### Query listings with filters and pagination Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/04-listings.md Example of how to query listings, applying filters for state and author, and setting pagination options. ```javascript const { UUID } = integrationSdk.types; integrationSdk.listings.query({ perPage: 20, page: 1, state: 'published', author: new UUID('user-uuid-here') }) .then(res => { res.data.forEach(listing => { console.log('Listing:', listing.attributes.title); }); }) .catch(err => { console.error('Query failed:', err.status); }); ``` -------------------------------- ### Money Type Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/types.md Demonstrates how to create and use the Money type from the SDK. ```javascript const { Money } = require('sharetribe-flex-integration-sdk').types; const price = new Money(5000, 'USD'); console.log("Amount in subunit (i.e. cents): " + price.amount) console.log("Currency: " + price.currency) ``` -------------------------------- ### File-based Token Storage Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Example of how to configure the SDK to use file-based token storage for persistence. ```javascript const sdk = integrationSdk.createInstance({ clientId: '...', clientSecret: '...', tokenStore: integrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### Special Methods Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Examples of special methods for authentication status and token revocation. ```javascript sdk.authInfo() // Returns current authentication status sdk.revoke() // Revokes authentication token ``` -------------------------------- ### POST /users/approve Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for approving a user. ```json { "id": {"uuid": "..."} } ``` -------------------------------- ### Adding Custom Type Handlers Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md Example of registering custom type handlers to support application-specific types within the SDK. ```javascript const sdk = integrationSdk.createInstance({ // ... typeHandlers: [ { sdkType: integrationSdk.types.UUID, appType: MyUUID, writer: (appValue) => new integrationSdk.types.UUID(appValue.value), reader: (sdkValue) => new MyUUID(sdkValue.uuid) } ] }); ``` -------------------------------- ### Query users with optional filters and pagination Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/03-users.md Example of querying users with specified perPage and page parameters. ```javascript integrationSdk.users.query({ perPage: 10, page: 1 }) .then(res => { res.data.forEach(user => { console.log('User:', user.attributes.email); }); console.log('Total:', res.meta.totalItems); }) .catch(err => { console.error('Query failed:', err.status); }); ``` -------------------------------- ### Fetch Listings Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/try-it-in-command-line.md JavaScript code to fetch and log the titles of the first 10 listings. ```javascript integrationSdk.listings.query({per_page: 10}).then(response => { console.log("Fetched " + response.data.data.length + " listings."); response.data.data.forEach(listing => { console.log(listing.attributes.title); }); }); ``` -------------------------------- ### POST /listings/update Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for updating an existing listing. ```json { "id": {"uuid": "..."}, "title": "Updated Title", "price": {"amount": 4500, "currency": "USD"}, "..." } ``` -------------------------------- ### Serve docpress docs Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Serves the documentation locally using Docpress. ```shell $ yarn run serve-docs ``` -------------------------------- ### Create a Listing Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Example of creating a new listing with attributes like title, description, price, location, and author, using SDK types for data formatting. ```javascript const { UUID, Money, LatLng } = integrationSdk.types; sdk.listings.create({ title: 'Mountain Bike', description: 'Excellent condition', price: new Money(15000, 'USD'), location: new LatLng(40.7128, -74.0060), author: new UUID('user-id-here') }) .then(res => { console.log('Listing created:', res.data.id); }) .catch(err => { console.error('Creation failed:', err.message); }); ``` -------------------------------- ### Publish to NPM (beta release) Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Publishes a beta version to NPM. ```bash npm publish --tag beta ``` -------------------------------- ### Build the package Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Builds the SDK package. ```shell $ yarn run build ``` -------------------------------- ### POST /users/update_permissions Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for updating user permissions and roles. ```json { "id": {"uuid": "..."}, "isAdmin": true, "..." } ``` -------------------------------- ### POST /users/update_profile Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for updating user profile information. ```json { "id": {"uuid": "..."}, "email": "newemail@example.com", "firstName": "Jane", "lastName": "Smith", "..." } ``` -------------------------------- ### Endpoint Definition Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md An example of an endpoint definition object, specifying API, path, method, and interceptors. ```javascript { apiName: 'integration_api', path: 'listings/query', internal: false, method: 'get', interceptors: [new TransitResponse()] } ``` -------------------------------- ### Build docpress docs Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Builds the documentation using Docpress. ```shell $ yarn run build-docs ``` -------------------------------- ### SDK Function Generation - GET Methods Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/architecture.md Characteristics of SDK functions generated from GET endpoint definitions. ```text GET methods: - Accept single `params` parameter - Apply queryLimiter if configured - Return Promise ``` -------------------------------- ### POST /users/verify_email Request Body Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example JSON request body for verifying a user's email address. ```json { "id": {"uuid": "..."}, "token": "verification-token" } ``` -------------------------------- ### Resource Command Methods (POST) Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Examples of POST methods for various resources like users, listings, transactions, images, and availability exceptions. ```javascript sdk.users.updateProfile(params, queryParams, perRequestOpts) sdk.users.approve(params, queryParams) sdk.users.updatePermissions(params, queryParams) sdk.users.verifyEmail(params, queryParams) sdk.listings.create(params, queryParams, perRequestOpts) sdk.listings.update(params, queryParams, perRequestOpts) sdk.listings.approve(params, queryParams) sdk.listings.open(params, queryParams) sdk.listings.close(params, queryParams) sdk.transactions.transition(params, queryParams, perRequestOpts) sdk.transactions.transitionSpeculative(params, queryParams, perRequestOpts) sdk.transactions.updateMetadata(params, queryParams, perRequestOpts) sdk.images.upload(params, queryParams, perRequestOpts) sdk.availabilityExceptions.create(params, queryParams, perRequestOpts) sdk.availabilityExceptions.delete(params, queryParams) sdk.stockAdjustments.create(params, queryParams, perRequestOpts) sdk.stock.compareAndSet(params, queryParams, perRequestOpts) ``` -------------------------------- ### Initialize with Rate Limiting Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Recommended way to initialize the SDK in production with rate limiting configurations for queries and commands, and a file-based token store. ```javascript const integrationSdk = require('sharetribe-flex-integration-sdk'); const sdk = integrationSdk.createInstance({ clientId: 'your-client-id', clientSecret: 'your-client-secret', queryLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodQueryLimiterConfig ), commandLimiter: integrationSdk.util.createRateLimiter( integrationSdk.util.prodCommandLimiterConfig ), tokenStore: integrationSdk.tokenStore.fileStore() }); ``` -------------------------------- ### Publish to NPM (stable release) Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Publishes a stable version to NPM. ```bash npm publish ``` -------------------------------- ### Custom Type Handler Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/your-own-types.md Example demonstrating how to configure type handlers for converting between SDK types (BigDecimal, LatLng, UUID) and custom application types (Decimal, google.maps.LatLng, own plain object UUID representation). ```javascript const { BigDecimal, LatLng } = require('sharetribe-flex-sdk').types; const integrationSdk = createInstance({ clientId: "", clientSecret: "", typeHandlers: [ { sdkType: BigDecimal, appType: Decimal, writer: v => new BigDecimal(v.toString()), reader: v => new Decimal(v.value), }, sdkType: LatLng, appType: google.maps.LatLng, writer: v => new LatLng(v.lat(), v.lng()), reader: v => new google.maps.LatLng(v.lat, v.lng) }, { sdkType: UUID, canHandle: v => v.isMyOwnUuidType, writer: v => new UUID(v.myOwnUuidValue), reader: v => ({myOwnUuidValue: v.uuid, isMyOwnUuidType: true}) } ] }); ``` -------------------------------- ### createInstance Configuration Options Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/configurations.md This code snippet demonstrates the various configuration options that can be passed to the `createInstance` method of the Sharetribe Flex SDK. ```javascript const sharetribeIntegrationSdk = require('sharetribe-flex-sdk'); var integrationSdk = sharetribeIntegrationSdk.createInstance({ // The API Client ID and client secret (mandatory) clientId: "", clientSecret: "", // List of custom type handlers typeHandlers: [ { sdkType: UUID, appType: MyUuidType, // Writer fn type signature must be: // appType -> sdkType // // E.g. // MyUuidType -> UUID writer: v => new UUID(v.myUuid), // Reader fn type signature must be: // sdkType -> appType // // E.g. // UUID -> MyUuidType reader: v => new MyUuidType(v.uuid), } ], // HTTP and HTTPS agents to be used when performing // http and https request. This allows defining non-default // options for agent, such as "{ keepAlive: false }$. // When creating custom httpsAgent, set `maxSockets` value to 10 or less. httpAgent: httpAgent, httpsAgent: httpsAgent, // For dev and demo marketplace environments, add query and command rate // limiters: queryLimiter: sharetribeIntegrationSdk.createRateLimiter( sharetribeIntegrationSdk.util.devQueryLimiterConfig ), commandLimiter: sharetribeIntegrationSdk.createRateLimiter( sharetribeIntegrationSdk.util.devCommandLimiterConfig ), // Token store tokenStore: sharetribeIntegrationSdk.tokenStore.memoryStore(), // SDK uses Transit format to communicate with the API. // If this configuration is `true` a verbose Transit mode is enabled. // Useful for development. // Default: false transitVerbose: false, // The API base URL (optional) // Defaults to Sharetribe production (https://flex-integ-api.sharetribe.com) // Change this if you want to point the SDK to somewhere else (like localhost). // Useful mainly for Sharetribe's internal development baseUrl: "https://the-api-base-url.example.sharetribe.com/", // Allow use of Client Secret in browser (optional, defaults to false) // // Sharetribe Integration SDK is meant to be used in a secure context, e.g. // in a private Node.js server. Using it in an open website exposes the // Client Secret to the public. // // By default, the SDK will display a warning if Client Secret is used in browser // but if you know what you are doing, and you have secured the website properly so // that Client Secret is not leaked, you can suppress the warning by setting this // to `true`. dangerouslyAllowClientSecretInBrowser: false }); ``` -------------------------------- ### Transition Transaction Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/05-transactions.md Transitions a transaction to a new state. ```javascript const { UUID } = integrationSdk.types; integrationSdk.transactions.transition({ id: new UUID('transaction-uuid-here'), transition: 'accept' }) .then(res => { console.log('Transition successful:', res.data.attributes); }) .catch(err => { console.error('Transition failed:', err.status); }); ``` -------------------------------- ### Show Transaction Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/05-transactions.md Retrieves a specific transaction by ID. ```javascript const { UUID } = integrationSdk.types; integrationSdk.transactions.show({ id: new UUID('transaction-uuid-here') }) .then(res => { console.log('Transaction:', res.data.attributes); }) .catch(err => { console.error('Failed to fetch transaction:', err.status); }); ``` -------------------------------- ### Get Authentication Info Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/09-auth-utilities.md Returns information about the current authentication status. ```typescript authInfo(): Promise ``` ```javascript integrationSdk.authInfo() .then(res => { if (res.grantType === 'refresh_token') { console.log('User is logged in with refresh token'); } else if (res.grantType === 'client_credentials') { console.log('User is logged in with client credentials'); } else { console.log('No active authentication'); } }) .catch(err => { console.error('Failed to get auth info:', err.status); }); ``` -------------------------------- ### Example of object query parameters without utility Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/object-query-parameters.md Demonstrates how to construct object query parameters manually for custom image variants. ```javascript integrationSdk.listings.show({ id: listingId, include: ["images"], "fields.image": ["variants.my-variant"], "imageVariant.my-variant": "w:640;h:1280;fit:scale" }).then(res => { // res.data contains the response data }); ``` -------------------------------- ### POST /images/upload Response Body Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example response body after uploading an image. ```json { "data": { "id": {"uuid": "..."}, "type": "image", "attributes": {} } } ``` -------------------------------- ### Usage Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/README.md Create a new SDK instance and query listings. ```javascript const sharetribeIntegrationSdk = require('sharetribe-flex-integration-sdk'); // Create new SDK instance const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId: '', clientSecret: '' }); // Query first 5 listings integrationSdk.listings .query({ perPage: 5 }) .then(res => { // Print listing titles res.data.data.forEach(listing => { console.log(`Listing: ${listing.attributes.title}`) }); }) .catch(res => { // An error occurred console.log(`Request failed with status: ${res.status} ${res.statusText}`); }); ``` -------------------------------- ### Query Transactions Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/05-transactions.md Queries transactions with optional filters and pagination. ```javascript const { UUID } = integrationSdk.types; integrationSdk.transactions.query({ perPage: 10, page: 1, listing: new UUID('listing-uuid-here') }) .then(res => { res.data.forEach(tx => { console.log('Transaction:', tx.id); }); }) .catch(err => { console.error('Query failed:', err.status); }); ``` -------------------------------- ### Query Listings with Pagination Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/README.md Example of querying listings with pagination parameters and handling the response, including total items and individual listing details. ```javascript sdk.listings.query({ perPage: 20, page: 1, state: 'published' }) .then(res => { console.log('Found', res.meta.totalItems, 'listings'); res.data.forEach(listing => { console.log(listing.attributes.title); }); }) .catch(err => { console.error('Query failed:', err.status, err.statusText); }); ``` -------------------------------- ### POST /auth/token - Response Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example response body for a successful authentication token request. ```json { "access_token": "...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "..." } ``` -------------------------------- ### POST /stock_adjustments/create Request Body Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example request body for creating a stock adjustment. ```json { "listing": {"uuid": "..."}, "quantity": 5, "reason": "Manual correction" } ``` -------------------------------- ### Update Github Pages Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Updates the documentation on Github Pages. ```shell git checkout master yarn run build-docs mv _docpress ../ git checkout gh-pages cp -r ../_docpress/* ./ rm -r ../_docpress git add . git commit -m "Update docs" git push --force git checkout master ``` -------------------------------- ### POST /availability_exceptions/create Request Body Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example request body for creating an availability exception. ```json { "listing": {"uuid": "..."}, "start": "2025-01-15T00:00:00Z", "end": "2025-01-20T23:59:59Z", "reason": "Owner vacation" } ``` -------------------------------- ### POST /transactions/update_metadata Request Body Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md Example request body for updating transaction metadata. ```json { "id": {"uuid": "..."}, "metadata": { "customField": "value" } } ``` -------------------------------- ### Authorization Header Example Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/endpoints.md All API requests require an Authorization header with a Bearer token. ```http Authorization: Bearer ``` -------------------------------- ### Run tests Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/developing-sdk.md Executes the test suite for the SDK. ```shell $ yarn test ``` -------------------------------- ### Dev and demo marketplace environments Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/docs/rate-limits.md Example configuration for client-side rate limits suitable for development and demo environments. ```javascript const sharetribeIntegrationSdk = require('sharetribe-flex-integration-sdk'); const queryLimiter = sharetribeIntegrationSdk.util.createRateLimiter( sharetribeIntegrationSdk.util.devQueryLimiterConfig ); const commandLimiter = sharetribeIntegrationSdk.util.createRateLimiter( sharetribeIntegrationSdk.util.devCommandLimiterConfig ); const integrationSdk = sharetribeIntegrationSdk.createInstance({ clientId: "", clientSecret: "", queryLimiter: queryLimiter, commandLimiter: commandLimiter, }); ``` -------------------------------- ### Update Transaction Metadata Source: https://github.com/sharetribe/flex-integration-sdk-js/blob/master/_autodocs/api-reference/05-transactions.md Example of how to update the metadata for a transaction using the SDK. ```javascript const { UUID } = integrationSdk.types; integrationSdk.transactions.updateMetadata({ id: new UUID('transaction-uuid-here'), metadata: { customField: 'customValue' } }) .then(res => { console.log('Metadata updated'); }) .catch(err => { console.error('Update failed:', err.status); }); ```