### Example Environment Variables for Development Setup Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/stripe.md Illustrates typical environment variable settings for a development environment, using test keys and lower purchase limits for testing purposes. ```bash STRIPE_API_KEY=sk_test_development_key COIN_PURCHASE_DAILY_LIMIT=10 ``` -------------------------------- ### JavaScript Example: Starting a Parking Session Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-park-mobile.js.md Illustrates how to initiate a parking session via an HTTP POST request to the '/api/v2/parking/start' endpoint, providing details such as price ID, license plate number, state, and payment type. ```javascript const postData = { price_id: uuid, lpn: 'ABC1234', lpnState: 'TX', payment_type: 'coin' }; const response = await httpClient.post('/api/v2/parking/start', postData, config); ``` -------------------------------- ### JavaScript Example for Token Integration in Test Setup Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/src/helpers/test.md Provides an example of integrating the `authToken` function within a test setup, specifically using a `beforeEach` hook. This illustrates how to obtain an authentication token for authenticated API requests in a testing framework. ```javascript // In test setup beforeEach(async () => { const userToken = await authToken(testUserId); // Use token for authenticated API requests }); ``` -------------------------------- ### Example Output: Development Environment Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/project.md This snippet shows the configuration object when the environment variables are set for a development setup, specifically `tsp-api-dev` for the project name and `development` for the stage. ```javascript { projectName: "tsp-api-dev", projectStage: "development" } ``` -------------------------------- ### Example Output of ParkMobile Configuration Load Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/parkmobile.md Provides examples of the JavaScript object structure returned when the ParkMobile configuration is loaded. It illustrates both the default values and how values are overridden when environment variables are set, showcasing the configuration's dynamic behavior. ```javascript // With default values { email: 'sophia_ting@metropia.com', slackChannel: 'C0500872XUY' } // With environment variables set { email: 'custom@company.com', slackChannel: 'C1122334455' } ``` -------------------------------- ### Common Database Configuration Error Examples Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/database.md Provides examples of common errors encountered during database configuration, such as missing environment variables, connection timeouts, and invalid configuration types. ```javascript // Missing environment variable Error: REDIS_CACHE_HOST environment variable is required // Connection timeout Error: Database connection timeout after 30000ms // Invalid configuration TypeError: Cannot read property 'mysql' of undefined ``` -------------------------------- ### JavaScript Example: Getting Parking Zone Rates Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-park-mobile.js.md Demonstrates how to make an HTTP GET request to the '/api/v2/parking/rate-zone' endpoint to retrieve parking rates for a specific zone, including necessary 'userid' header and 'zone' parameter. ```javascript const config = { headers: { userid: testUserId, 'Content-Type': 'application/json' }, params: { zone: testZone } }; const response = await httpClient.get('/api/v2/parking/rate-zone', config); ``` -------------------------------- ### JavaScript Example for Slack Configuration Usage Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/slack.md This JavaScript example demonstrates how to import and utilize the defined Slack configuration. It shows how to send a general system notification to the default channel and a specific vendor failure alert to a designated channel, using the configured bot token for authentication. ```javascript // How to import and use this configuration const slackConfig = require('./config/vendor/slack'); // Send notification to default channel const response = await axios.post('https://slack.com/api/chat.postMessage', { channel: slackConfig.channelId, text: 'System notification message' }, { headers: { 'Authorization': `Bearer ${slackConfig.token}` } }); // Send vendor failure alert to specific channel await notifyChannel(slackConfig.vendorFailedChannelId, 'Vendor service is down'); ``` -------------------------------- ### Example of Successfully Loaded AWS Configuration Object Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/aws.md Shows the structure and typical values of a successfully loaded AWS configuration object. This example illustrates how region, SQS queue URL, and S3 bucket name are populated when all settings are correctly provided. ```javascript { region: "us-east-1", sqs: { queueUrl: "https://sqs.us-east-1.amazonaws.com/123456789/myapp-queue" }, s3: { bucketName: "myapp-production-storage" } } ``` -------------------------------- ### Example Output of Successfully Loaded Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/default.md Shows a JavaScript object representation of the configuration after a successful load, highlighting key application, JWT, and portal settings with example values. This demonstrates the structure of the configuration object available to the application. ```javascript { app: { port: 8888, logLevel: 'info', debug: false, apiVersion: 'v2' }, jwtKey: 'prod_jwt_key_value', portal: { domainUrl: 'https://production-domain.com', welcomeCoin: '3.5', // ... other settings } } ``` -------------------------------- ### Example of Successfully Loaded HERE Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/here.md An example JavaScript object representing a successfully loaded HERE API configuration, including the API key and router URL. ```javascript { apiKey: "AbCdEf123456789...", // 84-character HERE API key router: "https://router.hereapi.com" } ``` -------------------------------- ### Notification Service Integration Response Example Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/parkmobile.md Demonstrates an example of calling a notification service with ParkMobile configuration details and shows the expected successful response object structure. This includes the `sent` status and a `timestamp`, indicating successful message delivery. ```javascript // Notification service usage const response = await notificationService.send({ type: 'parkmobile_error', contact: parkmobileConfig.email, channel: parkmobileConfig.slackChannel, message: 'Payment processing failed' }); // Response: { sent: true, timestamp: '2024-01-15T10:30:00Z' } ``` -------------------------------- ### Example Database Configuration Object Structure Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/database.md Shows the expected JSON structure of the `database` configuration object, detailing settings for MySQL (multiple instances), Redis, MongoDB, and InfluxDB. ```javascript { mysql: { portal: { host: 'portal-db', port: 3306, database: 'portal' }, houston: { host: 'houston-db', port: 3306, database: 'houston' }, gtfs: { host: 'gtfs-db', port: 3306, database: 'gtfs' }, admin: { host: 'admin-db', port: 3306, database: 'admin' }, carpooling: { host: 'carpool-db', port: 3306, database: 'carpooling' } }, redis: { cache: { host: 'redis-cache', port: 6379, password: '***' } }, mongo: { cache: { url: 'mongodb://mongo-cache:27017/cache' }, dataset: { url: 'mongodb://mongo-dataset:27017/dataset' } }, influx: { url: 'http://influxdb:8086', bucket: 'tsp-metrics', org: 'maas-platform' } } ``` -------------------------------- ### Example Seed Data Structure (JavaScript) Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/database/seeds/init.md This JavaScript object illustrates the structure of the core system data categories used for database seeding. It includes examples for `app_update` (app version requirements), `activity_type` (point transaction types), `travel_mode` (transportation definitions), and `auth_user` (test user accounts), demonstrating the initial data populated into the database. ```javascript // Core system data categories { app_update: [ { app_version: '1.97.3', app_os: 'android', is_required: 'T' }, { app_version: '1.3.2', app_os: 'ios', is_required: 'T' } ], activity_type: [ { id: 1, name: 'adjustment', description: 'Adjust coin' }, { id: 6, name: 'incentive', description: 'Incentive' }, // ... 11 total activity types ], travel_mode: [ { id: 1, name: 'driving' }, { id: 2, name: 'public_transit' }, { id: 100, name: 'duo' } // ... 8 total travel modes ], auth_user: [ { id: 1001, email: 'test2@metropia.com' } // ... 4 test users ] } ``` -------------------------------- ### JavaScript Test Configuration Setup Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test/test-campaign.md Provides the basic setup for the campaign test suite, including defining a test user ID and initializing the application, router, and supertest agent before running tests. This ensures a consistent testing environment. ```javascript describe('Campaign System', () => { const testUserId = 1003; const auth = { userid: testUserId, 'Content-Type': 'application/json' }; let app, router, request; before(async () => { app = createApp(); router = getRouter(); request = supertest.agent(app.listen()); }); }); ``` -------------------------------- ### JavaScript Usage Example: Applying Tier-Specific Benefits Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-tier.js.md Shows a JavaScript example of how to fetch tier-specific benefits using `tierService.getUserTierBenefits` and then apply them to calculate values like raffle entries and referral bonuses. It demonstrates how benefits can magnify base values. ```javascript const benefits = await tierService.getUserTierBenefits('bronze'); const raffleEntries = baseEntries * benefits.raffle.magnification; const referralBonus = baseReward * benefits.referral.magnification; ``` -------------------------------- ### JavaScript Example for OpenAI API Usage Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/openai.md Demonstrates how to import the OpenAI configuration and make a chat completion API request using axios. This example illustrates the process of sending a message to the 'gpt-3.5-turbo' model and logging the response, including setting necessary authorization and content-type headers. ```javascript // How to import and use this configuration const openaiConfig = require('./config/vendor/openai'); // Make API request to OpenAI const response = await axios.post(`${openaiConfig.apiUrl}/v1/chat/completions`, { model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: 'Hello, world!' }] }, { headers: { 'Authorization': `Bearer ${openaiConfig.apiKey}`, 'Content-Type': 'application/json' } }); console.log(response.data.choices[0].message.content); ``` -------------------------------- ### JavaScript Authentication Setup for API Tests Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-promocode.js.md Shows how to set up authentication headers with a Bearer token for API requests, dynamically fetching the token before tests run. ```javascript const userId = 1003; let auth = { userid: userId, 'Content-Type': 'application/json', authorization: '' }; before(async () => { const token = await authToken(userId); auth.authorization = `Bearer ${token}`; }); ``` -------------------------------- ### Example of Missing HERE API Key Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/here.md An example JavaScript object showing the state of the configuration when the API key is undefined, leading to downstream errors from HERE services. ```javascript { apiKey: undefined, router: "https://router.hereapi.com" } // Downstream error: "Invalid API key" from HERE services ``` -------------------------------- ### Example Output: Missing Environment Variables Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/project.md This snippet demonstrates the output when the required environment variables (`PROJECT_NAME`, `PROJECT_STAGE`) are not set. The properties `projectName` and `projectStage` will be `undefined`. ```javascript { projectName: undefined, projectStage: undefined } ``` -------------------------------- ### JavaScript: Setup Test User and Wallet Before Tests Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-tier-for-uber.js.md Initializes a dedicated test user and their associated wallet before running the unit tests. This setup ensures a clean and controlled environment for testing refund scenarios, including creating user records and populating wallet balances using the `knex` ORM. ```javascript const testUserId = 5566; before(async () => { // Create test user await knex('auth_user').insert({ id: testUserId, first_name: 'Test', last_name: 'User', email: 'test.refund@example.com', password: 'hashed_password', phone_number: '+1234567890', }); // Create test wallet [testWalletId] = await knex('user_wallet').insert({ user_id: testUserId, balance: 1000, auto_refill: 'F', below_balance: 5, stripe_customer_id: null, }); }); ``` -------------------------------- ### Example InfluxDB Line Protocol Data Point Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/database/influx.md Presents an example of a data point formatted in InfluxDB Line Protocol, as it would be written to the database. It includes the measurement name, tags (service, datacenter), fields (response_time), and a timestamp. ```text vendor_latency,service=tsp-api,datacenter=us-west-2 response_time=245.6 1640995200000000000 ``` -------------------------------- ### Example: Process Valid Referral with Error Handling (JavaScript) Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-referral-device-id.js.md Demonstrates how to call the `ReferralService.create` method with valid input data and includes basic error handling for device ID validation failures. This example showcases a typical API interaction flow. ```javascript const inputData = { userId: 1, referral_code: 'ABCDE12345', reward_type: 'token' }; try { const result = await ReferralService.create(inputData); console.log('Referral processed successfully'); } catch (error) { if (error.message === 'ERROR_REFERRAL_CODE_DEVICE_ID_NOT_EXIST') { console.log('Device ID validation failed'); } } ``` -------------------------------- ### Example TollGuru API Error Scenarios Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/tollguru.md This snippet shows examples of configuration issues, such as a missing API key, and mentions a common API error response like 401 Unauthorized, indicating authentication problems. ```javascript // Missing API key { apiKey: undefined, url: "https://apis.tollguru.com", source: "here" } // API Error Response: 401 Unauthorized ``` -------------------------------- ### JavaScript Example for Successful Promo Code Redemption Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-promocode.js.md This example demonstrates how to make a POST request to the `/api/v2/promocode` endpoint using JavaScript's `fetch` API, including necessary headers for content type and authorization, and illustrates the expected successful JSON response for a raffle ticket redemption. ```javascript const response = await fetch('/api/v2/promocode', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer jwt_token', 'userid': '1003' }, body: JSON.stringify({ promo_code: 'SUMMER2024' }) }); // Expected response: { "result": "success", "data": { "type": "raffle ticket", "toast": { "title": "Congratulations!", "message": "You're entered into the giveaway. Good luck!" } } } ``` -------------------------------- ### JavaScript Example: Creating an Instant Carpool Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-instant-carpoolings.js.md This example demonstrates how to programmatically create a new instant carpool using a POST request to the API. It sends origin, destination, and travel_time data, authenticated by a driver token. The response variable captures the API's reply. ```javascript const carpoolData = { origin: originObject, destination: destinationObject, travel_time: 1200 }; const response = await request .set(driverAuth) .post('/api/v2/instant-carpoolings') .send(carpoolData); ``` -------------------------------- ### Test Setup and Teardown with Sinon Sandbox Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test/test-trace.js.md Initializes a Sinon sandbox before each test to manage stubs, spies, and mocks, and restores the sandbox after each test to ensure a clean state. ```javascript let sandbox; beforeEach(() => { sandbox = sinon.createSandbox(); }); afterEach(() => { sandbox.restore(); }); ``` -------------------------------- ### JavaScript Carpool Details API Response Example Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-instant-carpoolings.js.md Provides an example of the JSON structure returned by the API when requesting carpool details. It includes the carpool's current status, an array of participating riders with their basic information, and a security key for validation. ```javascript const carpoolDetails = { status: 'waiting', riders: [{ user_id: 1003, first_name: 'passenger', last_name: 'duo', avatar: 'avatar_url' }], security_key: 'validation_key' }; ``` -------------------------------- ### Environment Variable Setup for HERE API Key Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/here.md Provides an example of setting the `HERE_API_KEY` environment variable for development purposes in a bash shell. ```bash # Development export HERE_API_KEY="your-dev-api-key-here" ``` -------------------------------- ### Example Output: Successful Project Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/project.md This snippet illustrates the expected output object when `PROJECT_NAME` and `PROJECT_STAGE` environment variables are successfully set, showing the populated `projectName` and `projectStage` properties. ```javascript { projectName: "tsp-api", projectStage: "production" } ``` -------------------------------- ### Example of Stripe Configuration with Default Values Applied Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/stripe.md Shows a Stripe configuration object where some values have been populated with defaults, indicating optional parameters that were not explicitly set. ```javascript { apiKey: 'sk_test_...', buyCoinLimit: '200', // Default applied buyCoinAlertLimit: '50', // Default applied webHookSecret: 'whsec_...', alertNotifyEmail: undefined // Optional, not set } ``` -------------------------------- ### GET /preference_default - Parking Preferences Response Structure Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-preference.md Example JSON structure returned for default parking preferences when querying with `type: 'parking'`. ```javascript // Query: { type: 'parking' } // Returns: DEFAULT_PREFERENCE.parking.parking { search_range: 500, navigation_show: true, vehicle_height: 0, price: 0, charged_limit: false, operations: [1, 2, 3, 4, 5, 6, 7, 8, 9] } ``` -------------------------------- ### Example of Configuration Validation Error Output Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/stripe.md Demonstrates the error message and stack trace generated when a required Stripe environment variable, such as STRIPE_API_KEY, is missing during application startup. ```javascript Error: STRIPE_API_KEY environment variable is required at Object. (/app/services/payment.js:15:11) ``` -------------------------------- ### GET /preference_default - Transport Preferences Response Structure Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-preference.md Example JSON structure returned for default transport preferences when querying with `type: 'transport'`. ```javascript // Query: { type: 'transport' } // Returns: DEFAULT_PREFERENCE.transport { choose_setting: 'normal', // Default setting mode normal: { transports: ['driving', 'walking'], path: 'best', road_types: ['motorways'] }, family: { /* family-specific settings */ }, travel: { /* travel-specific settings */ }, work: { /* work-specific settings */ } } ``` -------------------------------- ### Example Tango Card API Configuration Object Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/tango.md This JavaScript object literal provides a comprehensive example of a configuration structure used for integrating with the Tango Card API, typically for a test or development environment. It encapsulates various parameters such as API endpoints, platform credentials, account identifiers, email sender details, and thresholds for redemption limits and alerts. This object serves as a central repository for all necessary API interaction settings. ```javascript { url: 'https://integration-api.tangocard.com/raas/v2/', platformName: 'MetropiaTest', platformKey: 'lCbocjESjaU&jFoj!MgJOhiGaTnvmgzVQKMIroxyBuQBln', accountId: 'metrotest1', customerId: 'metrotest1', senderEmail: 'info@h-connectsmart.org', senderName: 'ConnectSmart', alertNotifyEmail: 'sibu.wang@metropia.com', insufficientLevel: '30', redeemLimit: '100', redeemAlertLimit: '50', emailTemplateId: 'E000000' } ``` -------------------------------- ### Mock Setup for DUO Carpool Passenger ETA Update Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test/test-trace.js.md Sets up mocks for DuoReservations.query to simulate a scenario where the user is a passenger in a scheduled carpool, expecting ETA updates to be rejected. ```javascript // Passenger role in reservation sandbox.stub(DuoReservations, 'query').returns({ where: sandbox.stub().returns({ first: sandbox.stub().resolves({ reservation_id: 'res-123', role: 2 // Passenger }) }) }); ``` -------------------------------- ### Referral Integration Test Setup Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-referral.js.md Initializes the test environment for referral system integration tests. It sets up user authentication, mocks the tier service, and generates valid and invalid referral codes using Hashids. ```javascript describe('Referral', async () => { const userId = 1003; let auth = { userid: userId, 'Content-Type': 'application/json', authorization: '' }; let referralCode, selfReferral; before('Prepare testing data', async () => { // Enable debug mode for test user await AuthUsers.query().where('id', userId).patch({ is_debug: 1 }); // Generate JWT token const token = await authToken(userId); auth.authorization = `Bearer ${token}`; // Mock tier service stub1 = sinon.stub(tierService, 'getUserTier') .resolves({ level: 'green', points: 1 }); // Generate referral codes const referralHash = new Hashids(config.projectTitle, 10); referralCode = referralHash.encode(1005); // Valid referrer selfReferral = referralHash.encode(1003); // Self-referral (invalid) }); }); ``` -------------------------------- ### API Performance Test Example (Mocha/Chai) Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-ridehail.md An example of an integration test using Mocha and Chai to measure API response time for a GET request. This test ensures that the API endpoint responds within a specified acceptable time limit (e.g., 5 seconds) for performance validation. ```javascript describe('Performance Tests', () => { it('should respond within acceptable time limits', async function () { this.timeout(10000); const startTime = Date.now(); const resp = await request .set(auth) .get(`/pickup_point?latitude=${lat}&longitude=${lng}`); const endTime = Date.now(); const responseTime = endTime - startTime; expect(resp.statusCode).to.eq(200); expect(responseTime).to.be.lessThan(5000); // 5 second max }); }); ``` -------------------------------- ### GET /preference_default - Single Preferences Response Structure Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-preference.md Example JSON structure returned for default single preferences (e.g., mass_transit) when querying with `type: 'single'` and `get_default: 'mass_transit'`. ```javascript // Query: { type: 'single', get_default: 'mass_transit' } // Returns: DEFAULT_PREFERENCE.single.mass_transit { transports: ['bus', 'subway', 'train'], path: 'trans_less' } ``` -------------------------------- ### Illustrate Knex CLI Command Output Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/knexfile.md These bash examples demonstrate the typical output when executing `npx knex migrate:latest` and `npx knex seed:run` commands. They show how Knex reports the status of migration batches and seed file executions, confirming successful database operations. ```bash $ npx knex migrate:latest Using environment: development Batch 1 run: 3 migrations $ npx knex seed:run Using environment: development Ran 2 seed files ``` -------------------------------- ### Testing ParkMobile Configuration with Environment Variables Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/parkmobile.md Illustrates how to test the ParkMobile configuration module's behavior under different environment variable scenarios using `node -e`. It shows the output when no variables are set and when partial variables are set, demonstrating configuration loading logic. ```bash # No environment variables set $ node -e "console.log(require('./config/vendor/parkmobile'))" { email: 'sophia_ting@metropia.com', slackChannel: 'C0500872XUY' } # Partial environment variables $ PARKMOBILE_CONTACT_EMAIL=test@example.com node -e "console.log(require('./config/vendor/parkmobile'))" { email: 'test@example.com', slackChannel: 'C0500872XUY' } ``` -------------------------------- ### API Documentation: Retrieve All Favorite Locations Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-favorites.md Documents the GET /favorites endpoint for retrieving all favorite locations for an authenticated user, including success/error scenarios and an example response structure. ```APIDOC Endpoint: GET /favorites Purpose: Retrieves all favorite locations for the authenticated user Success Scenario: - Returns array of user's favorites - Each favorite includes all required response keys - Validates data integrity against original creation data - Confirms at least one favorite exists after creation Response Structure: { "result": "success", "data": { "favorites": [ { "id": 123, "category": 1, "name": "unit test", "icon_type": null, "place_id": null, "access_latitude": 25.033969, "access_longitude": 121.564461, "longitude": 121.564461, "latitude": 25.033969, "created_on": "2023-01-01T00:00:00.000Z", "address": "No.7, Sec. 5, Xinyi Rd., Xinyi Dist., Taipei City 110, Taiwan (R.O.C.)", "modified_on": "2023-01-01T00:00:00.000Z" } ] } } Error Scenarios: - 10004: Missing authentication header ``` -------------------------------- ### Initialize MaaS Core CLI Program Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/app.md This JavaScript snippet demonstrates how to initialize the MaaS core platform's command-line interface. It retrieves the program instance, sets its version from `package.json`, and parses command-line arguments for service execution, acting as the core CLI setup. ```javascript const { getProgram } = require('@maas/core'); const program = getProgram(); program.version(pjson.version); program.parse(process.argv); ``` -------------------------------- ### JavaScript: Welcome Coin Configuration Loading Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-welcome-coin.md This snippet demonstrates how the welcome coin amount is loaded from the application's portal configuration. It highlights the use of a `config` module and parsing the value to a float, ensuring flexibility in setting the coin amount. ```javascript const config = require('config').portal; const welcomeCoinAmount = parseFloat(config.welcomeCoin); ``` -------------------------------- ### Example Response Structure for Get Gift Cards API Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-gift-cards.md Illustrates the expected JSON structure returned by the `GET /giftcards` API endpoint upon a successful request. It shows the top-level `result` and `data` fields, with the `data` object containing a `giftcards` array. Each gift card entry includes `category_id`, `name`, `image`, and a nested `items` array, detailing individual gift card options with `id`, `currency`, `amount`, `points`, and `display_rate`. ```javascript { "result": "success", "data": { "giftcards": [ { "category_id": 1, "name": "Retail Gift Cards", "image": "https://example.com/category-image.jpg", "items": [ { "id": 101, "currency": "USD", "amount": 25.00, "points": 2500, "display_rate": "100 points = $1" } ] } ] } } ``` -------------------------------- ### JavaScript Mock ParkMobile Session Activation API Response Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-park-mobile.js.md Example JavaScript object representing a successful response from the ParkMobile session activation API. It provides the session ID, license plate number (LPN), zone, pricing details, and UTC timestamps for session start, stop, and creation. ```javascript const successRateActivateResponse = { sessionId: 'IC73443624523235N', lpn: fakeLpn, zone: `${hardcodedArea}${testZone}`, price: { parkingPrice: 0, transactionFee: 0, totalPrice: 0 }, startTimeUTC: moment.utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z', stopTimeUTC: moment.utc().add(1, 'hours').format('YYYY-MM-DDTHH:mm:ss') + 'Z', createdAt: moment.utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z' }; ``` -------------------------------- ### Mock Event Data Structure Example Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-incident-event-service.md This snippet defines a JavaScript object representing a mock event data structure. It includes various properties like `_id`, `event_id`, `description`, `expires`, `lat`, `lon`, `location`, `polygon`, `reroute`, `start`, and `type`, which are used for simulating and testing event-related functionalities within the system. ```javascript const testEvent = { _id: 'TESTConst1234567', event_id: 'TESTConst1234567', close: false, description: 'Closed continuously until 5:00 PM, Friday, April 7', expires: '2024-01-23T03:24:26.143Z', lat: -29.540446, lon: -95.019508, location: 'SH-146 Northbound At 9Th St (Closed continuously until 5:00 PM, Friday, April 7)', polygon: [/* complex polygon coordinates */], reroute: 1, start: '2023-03-06T13:00:00', type: 'Closure' }; ``` -------------------------------- ### 14. Get Members - GET /duo_group/member Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-duo-group.md Retrieves paginated list of group members. ```APIDOC Endpoint: GET /duo_group/member Purpose: Retrieves paginated list of group members Success Scenario: - Returns member list with user details and ratings - Includes security key and pagination data - Shows member profiles and blacklist status Error Scenarios: 10004: Missing authentication 21003: Group not found ``` -------------------------------- ### 15. Get Member Profile - GET /duo_group/member_profile Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-duo-group.md Retrieves detailed profile of a specific member. ```APIDOC Endpoint: GET /duo_group/member_profile Purpose: Retrieves detailed profile of a specific member Success Scenario: - Returns comprehensive member profile - Includes vehicle info, social media, and ride statistics - Shows matching compatibility and blacklist status Error Scenarios: 10004: Missing authentication 10001: Required user_id parameter 20001: Member profile not found ``` -------------------------------- ### Hashids Configuration and Usage Example (JavaScript) Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-referral.js.md This snippet illustrates the configuration and usage of the `Hashids` library. It shows how to initialize `Hashids` with a project-specific salt and minimum hash length, and how to decode a referral code back into the original user ID. ```javascript const referralHash = new Hashids(config.projectTitle, 10); const userId = referralHash.decode(referralCode)[0] || 0; ``` -------------------------------- ### API Endpoint: Get Gift Cards - GET /giftcards Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-gift-cards.md Documents the `GET /giftcards` API endpoint, detailing its purpose, expected success response, and specific error scenarios. This endpoint is designed to retrieve all available gift card categories and their associated redemption options, including pricing and points information. ```APIDOC Endpoint: GET /giftcards Purpose: Retrieves all available gift card categories and redemption options Success Scenario: - Returns complete gift card catalog - Includes categories with nested items - Validates data structure and required fields - Confirms at least one gift card category exists Error Scenarios: - 10004: Missing authentication header (userid required) ``` -------------------------------- ### Execute Knex CLI Commands for Database Operations Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/knexfile.md This section provides common `npx knex` command-line interface examples for managing database migrations and seeds. It covers running, rolling back, and creating new migration and seed files, essential for database schema evolution and data population. ```bash # Run migrations npx knex migrate:latest # Rollback migrations npx knex migrate:rollback # Run seeds npx knex seed:run # Create new migration npx knex migrate:make migration_name # Create new seed npx knex seed:make seed_name ``` -------------------------------- ### API Endpoint: GET /preference Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-preference.md Documentation for the GET /preference API endpoint, used to retrieve a user's current preferences. Defaults to system defaults if not customized. ```APIDOC GET /preference Purpose: Retrieves user's current preferences (defaults to system defaults if not customized) Structure: Same as default preferences but returns user-specific overrides if they exist ``` -------------------------------- ### API Endpoint: GET /preference_default Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-preference.md Documentation for the GET /preference_default API endpoint, used to retrieve default preference configurations. Includes query parameters and expected preference types. ```APIDOC GET /preference_default Purpose: Retrieves default preference configurations Query Parameters: type: Preference category ('transport', 'single', 'parking') get_default: Specific preference name (for 'single' type) ``` -------------------------------- ### Basic Database Configuration Access in JavaScript Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/database.md Demonstrates how to import and access specific database configurations (MySQL, Redis) from a central `database.js` file using `require`. ```javascript const database = require('./config/database'); // Access specific database configuration const mysqlConfig = database.mysql; const redisConfig = database.redis; ``` -------------------------------- ### Integrating Project Configuration into Main Application Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/vendor/project.md This JavaScript example shows how the project-specific configuration can be integrated into a larger, main application configuration object. It demonstrates how to nest the `projectName` and `projectStage` under a `service` property, providing a structured approach to application settings. ```javascript const project = require('./vendor/project'); module.exports = { service: { name: project.projectName, environment: project.projectStage, // ... other config } }; ``` -------------------------------- ### Carpool API Suggested Price - Input Parameters Example Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test/test-carpool.md An example JavaScript object representing the input parameters for the `/suggested_price` endpoint. It specifies the `meter` (distance) and `country` for the pricing calculation. ```javascript { meter: 1000, country: 'usa' } ``` -------------------------------- ### JSON Example for Invalid Promo Code Error Response Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/test-promocode.js.md This snippet provides an example of the JSON response structure returned by the API when an invalid promo code is submitted, detailing the specific error code and message. ```json // Invalid code response: { "result": "fail", "error": { "code": 46001, "msg": "Oops, the promo code you entered is not valid." } } ``` -------------------------------- ### Example .env File for Configuration Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/default.md Provides a sample `.env` file detailing essential, database-related, and optional environment variables required or used by the application's configuration module. This file is typically used for local development or containerized deployments to manage secrets and settings. ```env # Essential JWT_KEY=your_jwt_secret_key_here PROTAL_DOMAIN=your-domain.com MAIL_SERVER=https://your-mail-service.com # Database (see database.js) DB_HOST=localhost DB_USER=tsp_user DB_PASSWORD=secure_password # Optional with defaults APP_PORT=8888 APP_LOG_LEVEL=info WELCOME_COIN=3.5 ``` -------------------------------- ### Node.js TSP API Main Module Initialization Pattern Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/src/index.md This JavaScript code snippet illustrates a typical implementation pattern for the main index module of a Node.js application, specifically for the TSP API. It demonstrates how to require core components like 'bootstraps', 'routes', and 'services', and then defines an asynchronous 'initialize' function responsible for setting up services and applying routes. The module exports this 'initialize' function, making it the primary entry point for application startup. ```javascript // Typical implementation pattern const app = require('./bootstraps'); const routes = require('./routes'); const services = require('./services'); // Initialize application async function initialize() { await services.init(); app.use(routes); return app; } module.exports = initialize; ``` -------------------------------- ### Examples of MongoDB Database Operation Results Source: https://github.com/howard-metropia/knowledge-connectsmart-tsp-api/blob/master/config/database/mongo.md Provides examples of typical results from various MongoDB operations, including the `acknowledged` status and `insertedId` for inserts, an array of documents for find operations, and aggregated counts. ```javascript // Insert operation { acknowledged: true, insertedId: ObjectId('...') } // Find operation [ { _id: ObjectId('...'), userId: '12345', timestamp: 2024-01-15T10:30:00.000Z }, { _id: ObjectId('...'), userId: '12345', timestamp: 2024-01-15T09:15:00.000Z } ] // Count operation { totalTrips: 247, cacheEntries: 1503 } ```