### Example Notification Service Integration and Response in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parkmobile.md Demonstrates a call to a `notificationService` using ParkMobile configuration details and shows an example of the successful response object received, indicating the outcome of the notification attempt. ```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 of Development Environment AWS Configuration Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/aws.md Provides a specific example of the AWS configuration object tailored for a development environment, showing typical values for region, SQS, and S3. ```javascript { region: "us-west-2", sqs: { queueUrl: "https://sqs.us-west-2.amazonaws.com/123456789/dev-notifications" }, s3: { bucketName: "tsp-api-dev-uploads" } } ``` -------------------------------- ### TSP API Test Suite Setup Procedures Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-enterprise.md This section details the 'Before Hook' operations performed to set up the environment and data required for the TSP API test suite. It includes steps for authentication, organization creation, domain configuration, area setup, group creation, enterprise association, and member setup. ```APIDOC 1. Token Retrieval: Fetches Bearer token from AuthUsers table 2. Organization Creation: Creates test organization in org_setting 3. Domain Setup: Adds domain validation record 4. Area Configuration: Creates geographic area record 5. Group Creation: Sets up duo group for enterprise 6. Enterprise Association: Links user to enterprise with verification 7. Member Setup: Adds users to duo group with different roles ``` -------------------------------- ### Stripe Configuration for Development Environment Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/stripe.md Provides an example of environment variables specifically tailored for a development setup, using a test API key and lower purchase limits for testing purposes. ```bash STRIPE_API_KEY=sk_test_development_key COIN_PURCHASE_DAILY_LIMIT=10 ``` -------------------------------- ### JavaScript: Integrating Token Generation into Test Setup Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/src/helpers/test.md Provides an example of how to integrate the `authToken` function into a test setup, specifically within a `beforeEach` hook. This ensures an authenticated user token is available for subsequent API requests in tests. ```javascript // In test setup beforeEach(async () => { const userToken = await authToken(testUserId); // Use token for authenticated API requests }); ``` -------------------------------- ### Integration Test Setup for Referral System (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-referral.js.md Initial setup for the referral system integration tests, including user authentication, JWT token generation, mocking of tier service, and generation of valid/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) }); }); ``` -------------------------------- ### JavaScript Example for Sending Slack Notifications Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/slack.md Demonstrates how to import the Slack configuration and use it to send messages to Slack channels. It includes examples for sending a general system notification to the default channel and a vendor failure alert to a specific channel, utilizing 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 Development Environment Configuration Output Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/project.md Provides an example of the configuration object when environment variables are specifically set for a development environment, showing typical values like 'tsp-api-dev' and 'development'. ```javascript { projectName: "tsp-api-dev", projectStage: "development" } ``` -------------------------------- ### Knex CLI Output Examples Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/knexfile.md Illustrates typical output when executing Knex CLI commands for migrations and seeds. These examples show the successful execution messages for applying the latest migrations and running seed files, indicating the environment used and the number of operations performed. ```bash $ npx knex migrate:latest Using environment: development Batch 1 run: 3 migrations $ npx knex seed:run Using environment: development Ran 2 seed files ``` -------------------------------- ### JavaScript API Request Setup Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-user-actions.md Initializes authentication headers and constructs the URL for making user action API requests. This setup is crucial for ensuring requests are properly authenticated and directed to the correct endpoint. ```javascript const auth = { userid: 1003, 'Content-Type': 'application/json' }; const url = router.url('addUserActions'); ``` -------------------------------- ### Set Production HERE API Key and Start Application Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/here.md This command demonstrates how to set the `HERE_API_KEY` environment variable before starting a Node.js application. It ensures the production API key is available to the application at runtime, preventing hardcoding. ```shell HERE_API_KEY="your-prod-api-key-here" npm start ``` -------------------------------- ### API Testing Environment Setup Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-tolls.md This snippet demonstrates the initial setup for API testing using `supertest` and `@maas/core`. It initializes the application, router, and a supertest agent for making HTTP requests. ```javascript const createApp = require('@maas/core/api'); const { getRouter } = require('@maas/core'); const { authToken } = require('@app/src/helpers/test'); const app = createApp(); const router = getRouter(); const request = supertest.agent(app.listen()); ``` -------------------------------- ### API Endpoint: GET /welcome_coin for Welcome Coin Distribution Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-welcome-coin.md Documents the GET /welcome_coin API endpoint, detailing its purpose to distribute welcome coins to new users. It specifies authentication requirements, business logic for first-time versus subsequent access, and transaction tracking. ```APIDOC GET /welcome_coin Purpose: Distributes welcome coins to new users on first access Authentication Required: Yes (userid header) Business Logic: 1. First Access: User receives configured welcome coin amount 2. Subsequent Access: User receives 0 coins (already claimed) 3. Tracking: Transaction recorded in WelcomeCoinHistory ``` -------------------------------- ### JavaScript API Test Environment Setup Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-routes.md Initializes the API application, router, and `supertest` agent for HTTP request testing. This setup is crucial for simulating client requests against the running API. ```javascript const createApp = require('@maas/core/api'); const { getRouter } = require('@maas/core'); const app = createApp(); const router = getRouter(); const request = supertest.agent(app.listen()); ``` -------------------------------- ### Card Creation API Request Body Example Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/test-card-setting.md Example JSON payload for creating a new payment card via the POST /card_setting endpoint, including a Stripe test token for transaction processing. ```javascript { transaction_token: 'tok_visa' } ``` -------------------------------- ### JavaScript OpenAI API Chat Completion Example Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/openai.md Demonstrates how to import the OpenAI configuration and make a chat completion request using Axios. This example shows how to set authorization headers, specify the model, and process the API response. ```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); ``` -------------------------------- ### Example of Stripe Configuration with Default Values Applied Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/stripe.md Illustrates a Stripe configuration object where some values have been populated with defaults, such as `buyCoinLimit` and `buyCoinAlertLimit`, and optional fields may be undefined. ```javascript { apiKey: 'sk_test_...', buyCoinLimit: '200', // Default applied buyCoinAlertLimit: '50', // Default applied webHookSecret: 'whsec_...', alertNotifyEmail: undefined // Optional, not set } ``` -------------------------------- ### Authentication Token Setup for Test Requests Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-promocode.js.md Demonstrates how to set up the authentication header with a Bearer token for test requests. It includes fetching a token asynchronously before tests run and assigning it to the `auth` object. ```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 Logging Integration Output Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/project.md Demonstrates how the project configuration (name and stage) can be integrated into application logs, providing contextual information for messages and aiding in debugging and monitoring. ```text [2024-01-15 10:30:45] INFO [tsp-api:production] Service started successfully [2024-01-15 10:30:45] INFO [tsp-api:production] Environment configuration loaded ``` -------------------------------- ### Example of Successfully Loaded HERE API Configuration Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/here.md This object represents a typical successful configuration loaded for the HERE API. It includes a placeholder for the 84-character API key and the base URL for the HERE routing service. ```json { "apiKey": "AbCdEf123456789...", "router": "https://router.hereapi.com" } ``` -------------------------------- ### JSON Response Example: Successful GET /giftcards Catalog Retrieval Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-gift-cards.md This JavaScript code snippet provides an example of the successful JSON response structure for the `GET /giftcards` API call. It demonstrates the hierarchical organization of gift card data, including top-level categories and their nested redemption items with detailed attributes like currency, amount, and points. ```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" } ] } ] } } ``` -------------------------------- ### Example .env File for Application Configuration Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Provides a sample .env file detailing essential and optional environment variables required for the application's operation, including JWT keys, domain settings, mail server, and database credentials. This file is typically used for local development or containerized deployments. ```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 ``` -------------------------------- ### JSON Example for Promo Code Error Response Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-promocode.js.md This snippet provides an example of a JSON error response returned by the API when an invalid promo code is submitted. It includes a specific error code (46001) and a user-friendly message to guide the client on the issue. ```json { "result": "fail", "error": { "code": 46001, "msg": "Oops, the promo code you entered is not valid." } } ``` -------------------------------- ### Example Output of ParkMobile Configuration Object in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parkmobile.md Illustrates the structure and values of the ParkMobile configuration object, showing both default values and values overridden by environment variables, providing insight into the module's output. ```javascript // With default values { email: 'sophia_ting@metropia.com', slackChannel: 'C0500872XUY' } // With environment variables set { email: 'custom@company.com', slackChannel: 'C1122334455' } ``` -------------------------------- ### Example Output with Missing Environment Variables Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor.md This JavaScript object illustrates the state of the configuration when required environment variables are not set. It shows `undefined` values for critical configuration parameters, indicating that services relying on these settings will likely fail to initialize or operate correctly. ```javascript { aws: { region: undefined, sqs: { queueUrl: undefined } }, stripe: { secretKey: undefined } // Services will fail to initialize properly } ``` -------------------------------- ### Stripe Customer Deletion Code Example Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/test-card-setting.md A JavaScript code snippet demonstrating how to programmatically delete a Stripe customer using the Stripe API, typically used in test setups to simulate specific error conditions. ```javascript const stripe = Stripe(stripeConfig.apiKey); const customer = await stripe.customers.del(userStripe.stripe_customer_id); ``` -------------------------------- ### JavaScript Example of Successful Configuration Object Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Shows a JSON-like representation of the configuration object after a successful load, highlighting key application, JWT, and portal settings with their respective values. This represents the runtime state of the configuration. ```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 } } ``` -------------------------------- ### Initialize and Perform Basic Redis Operations (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database/redis.md Demonstrates how to initialize an ioredis client with a configuration and perform basic `SET` and `GET` operations for session management. ```javascript const redisConfig = require('./config/database/redis'); const Redis = require('ioredis'); // Initialize Redis client const client = new Redis(redisConfig.cache); // Basic operations await client.set('session:user123', JSON.stringify(userData), 'EX', 3600); const session = await client.get('session:user123'); ``` -------------------------------- ### JavaScript: Mock Transit Alert Data Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-reservation-uis-alert.js.md Example JavaScript array demonstrating the structure of mock transit alert events used for testing. It includes various scenarios like ongoing alerts, future expiration, and expired alerts, showcasing the `event_id`, `type`, `effect_name`, `header_text`, `severity`, `start`, and `expires` properties. ```javascript const mockAlerts = [ { event_id: 12344, type: 'TEST', effect_name: 'Delay', header_text: 'Minor delays on the Red Line...', severity: 'Information', start: moment.utc().unix(), // Ongoing expires: 0, // No expiration }, { event_id: 12345, effect_name: 'Delay', start: moment.utc().unix(), expires: moment.utc().add(1, 'month').unix(), // Future expiration }, { event_id: 12346, start: moment.utc().unix(), expires: moment.utc().add(-9, 'minute').unix(), // Expired } ]; ``` -------------------------------- ### Load Welcome Coin Amount from Configuration (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-welcome-coin.md Demonstrates how the welcome coin amount is loaded from the application's portal configuration file. It highlights the use of `require('config')` and `parseFloat` to retrieve and parse the configurable coin value. ```javascript const config = require('config').portal; const welcomeCoinAmount = parseFloat(config.welcomeCoin); ``` -------------------------------- ### JavaScript: User Setup for Integration Tests Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-instant-carpoolings.js.md Initializes driver and rider user IDs and their corresponding authentication objects, including `userid` and `Content-Type` headers, for use in integration tests. ```javascript const driverId = 1005; const riderId = 1003; let driverAuth = { userid: driverId, 'Content-Type': 'application/json' }; let riderAuth = { userid: riderId, 'Content-Type': 'application/json' }; ``` -------------------------------- ### JavaScript: Example Carpool Details API Response Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-instant-carpoolings.js.md Illustrates the expected structure of a carpool details API response, including status, a list of riders with their details, 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' }; ``` -------------------------------- ### Initializing Services with Vendor Configurations Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor.md This example illustrates how to use the imported vendor configurations to initialize third-party service SDKs. It specifically shows initializing an AWS S3 client using the `aws.s3` configuration object, demonstrating the practical application of the centralized configuration. ```javascript const { aws, stripe, google } = require('./config/vendor'); const AWS = require('aws-sdk'); const awsS3 = new AWS.S3(aws.s3); ``` -------------------------------- ### JavaScript Mock Data for createAlert Function Test Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/test-mock-weather.js.md Example mock data used in test cases for the `mockWeather.createAlert` function. This JavaScript object simulates the input payload for creating a new weather alert, specifying its start time, end time, and the impacted geographical area. ```javascript const mockData = { data: { startAt: '2023-04-01T00:00:00Z', endAt: '2023-04-02T00:00:00Z', impactedArea: 'Test Area' } }; ``` -------------------------------- ### JavaScript Configuration Integration with JWT and Portal Settings Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Illustrates how to integrate the loaded configuration object with other application logic, specifically demonstrating its use with a JWT library for token signing and constructing URLs based on portal settings. ```javascript const config = require('./config/default'); const jwt = require('jsonwebtoken'); // Using JWT configuration const token = jwt.sign(payload, config.jwtKey); // Using portal settings const redirectUrl = `${config.portal.domainUrl}/redirect`; ``` -------------------------------- ### JavaScript Configuration Differences Between Development and Production Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Compares the `portal.domainUrl` setting in development versus production environments, demonstrating how environment variables dynamically alter configuration values to suit different deployment contexts. ```javascript // Development { portal: { domainUrl: 'http://localhost:8888' } } // Production (with PROTAL_DOMAIN=app.example.com) { portal: { domainUrl: 'https://app.example.com' } } ``` -------------------------------- ### Example Database Configuration Object Structure (JSON) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database.md Shows the expected JSON structure of the `database.js` configuration file, detailing settings for MySQL, Redis, MongoDB, and InfluxDB, including hosts, ports, databases, URLs, and credentials. ```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' } } ``` -------------------------------- ### Node.js TSP API Core Application Initialization Pattern Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/src/index.md This JavaScript code snippet demonstrates a typical Node.js pattern for initializing a TSP API application. It illustrates how to import core modules like bootstraps, routes, and services, and defines an asynchronous `initialize` function responsible for setting up services and applying routes. This function is then exported as the module's main entry point, coordinating the application's startup sequence. ```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; ``` -------------------------------- ### Basic Database Configuration Integration (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database.md Demonstrates how to import and access specific database configurations (MySQL, Redis) from a central `database.js` file. ```javascript const database = require('./config/database'); // Access specific database configuration const mysqlConfig = database.mysql; const redisConfig = database.redis; ``` -------------------------------- ### Examples of MongoDB Connection and Database Errors Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database/mongo.md This snippet presents common error messages encountered during MongoDB operations. It shows examples of authentication failures (`MongoServerError`) and 'Database not found' errors (`MongoError`), along with suggested resolutions for each. ```javascript // Connection error MongoServerError: Authentication failed // Resolution: Check MongoDB credentials in environment // Database not found MongoError: Database 'cache' not found // Resolution: Ensure database exists or auto-creation is enabled ``` -------------------------------- ### 14. Get Members - GET /duo_group/member Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-duo-group.md Retrieves a paginated list of group members. The response includes user details, ratings, security keys, and pagination data, along with member profiles and blacklist status. ```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 ``` -------------------------------- ### Import and Log ParkMobile Configuration in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parkmobile.md Demonstrates how to import the ParkMobile vendor configuration module and access its properties like email and Slack channel for basic logging or debugging purposes. ```javascript const parkmobileConfig = require('./config/vendor/parkmobile'); console.log(parkmobileConfig.email); // sophia_ting@metropia.com console.log(parkmobileConfig.slackChannel); // C0500872XUY ``` -------------------------------- ### Initialize AWS SDK Clients with Configuration Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/aws.md Illustrates how to use the loaded AWS configuration to initialize S3 and SQS clients from the AWS SDK, setting region and specific service parameters. ```javascript const AWS = require('aws-sdk'); const awsConfig = require('./config/vendor/aws'); // S3 client configuration const s3 = new AWS.S3({ region: awsConfig.region, params: { Bucket: awsConfig.s3.bucketName } }); // SQS client configuration const sqs = new AWS.SQS({ region: awsConfig.region, apiVersion: '2012-11-05' }); ``` -------------------------------- ### Initialize MaaS Core CLI Program Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/app.md This JavaScript snippet demonstrates how to initialize the command-line interface program using the `@maas/core` library. It retrieves the program instance, sets its version from a `pjson` (package.json) variable, and parses command-line arguments to prepare for service execution. ```javascript const { getProgram } = require('@maas/core'); const program = getProgram(); program.version(pjson.version); program.parse(process.argv); ``` -------------------------------- ### JavaScript: Integration Test User Setup and Teardown Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-tickets.js.md Defines the setup and teardown logic for integration tests, including creating a temporary user before tests run and deleting the user after tests complete, ensuring a clean test environment. ```javascript describe('integration test ticket related api', () => { let userId = 0; before(async () => { userId = await knex('auth_user').insert({}, ['id']); }); after(async () => { await knex('auth_user').where({ id: userId }).delete(); }); }); ``` -------------------------------- ### Import Stripe Configuration and Initialize Client in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/stripe.md Demonstrates how to import the Stripe configuration from a local file and initialize the Stripe client using the retrieved API key. ```javascript const stripeConfig = require('./config/vendor/stripe'); const stripe = require('stripe')(stripeConfig.apiKey); ``` -------------------------------- ### Example UberFareEstimation Record Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-uber-fare.md This snippet provides a concrete example of a `UberFareEstimation` data record, illustrating the typical values and format for each field, including a UUID for `fare_id`, currency details, and timestamps. ```APIDOC { fare_id: 'f47ac10b-58cc-4372-a567-0e02b2c3d479', product_id: '9c0fd086-b4bd-44f1-a278-bdae3cdb3d9f', fare_currency: 'TWD', fare_display: 'NT$190', fare_value: 195, modified_at: '2024-04-09T08:11:01.794Z', no_cars_available: false, pickup_eta: 5, product_display: 'UberX', trip_duration: 17 } ``` -------------------------------- ### JavaScript: Example of Processing a Complex Refund Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-tier-for-uber.js.md Provides a usage example of the `refundWithBenefit` function, demonstrating how to process a complex refund scenario with estimated fare, actual fare, and tier benefit. It also outlines the expected financial outcomes. ```javascript await refundWithBenefit( userId, 13.45, // Estimated fare 5.17, // Actual fare 4.00, // Tier benefit 'Complex refund scenario' ); // Expected outcomes: // - User refund: $8.28 // - Benefit used: $4.00 // - User pays: $1.17 out of pocket ``` -------------------------------- ### Example Usage of Parking Service Configurations in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parking.md Demonstrates how to import and utilize the configured parking service parameters for making API requests to ParkingLotApp (Taiwan), Inrix ParkMe (US), and Smarking (Houston) using Axios. ```javascript // How to import and use this configuration const parkingConfig = require('./config/vendor/parking'); // Taiwan - ParkingLotApp integration const parkingLotResponse = await axios.get(`${parkingConfig.parkinglotapp.url}/api/parking`, { params: { client_id: parkingConfig.parkinglotapp.auth.client_id, client_secret: parkingConfig.parkinglotapp.auth.client_secret } }); // US - Inrix ParkMe integration const inrixAuth = await axios.post(`${parkingConfig.inrix.auth_url}/auth`, { appId: parkingConfig.inrix.auth.appId, hashToken: parkingConfig.inrix.auth.hashToken }); // Houston - Smarking integration const smarkingData = await axios.get(`${parkingConfig.smarking.url}/api/spots`, { headers: { 'Authorization': `Bearer ${parkingConfig.smarking.auth.token}` } }); ``` -------------------------------- ### Common Database Configuration Error Examples (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database.md Illustrates typical error messages encountered during database configuration, such as missing environment variables, connection timeouts, and invalid configuration object access. ```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 ``` -------------------------------- ### 15. Get Member Profile - GET /duo_group/member_profile Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-duo-group.md Retrieves the detailed profile of a specific member. The profile includes comprehensive information such as vehicle details, social media links, ride statistics, matching compatibility, and blacklist status. ```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 ``` -------------------------------- ### JavaScript Example of Configuration with Missing JWT Key Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Illustrates the state of the configuration object when a critical environment variable like JWT_KEY is missing, showing it as `undefined`. This highlights a potential point of failure for authentication operations. ```javascript { jwtKey: undefined, // Will cause authentication failures // Application may start but JWT operations will fail } ``` -------------------------------- ### JavaScript: Unit Test Setup for Pass Usage Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-passuse.js.md Initial setup for the unit tests of the `passUse` service, defining a context object for requests and initializing variables like user ID and pass UUID. ```javascript describe('unit test for passUse', () => { const ctx = { request: { method: 'POST', path: '/api/v2/transit_payment/pass_use', } }; let stub1; const userId = 1003; const pass_uuid = 'pass_uuid'; }); ``` -------------------------------- ### MongoDB Test Data Setup for Integration Tests Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-incident-event.md This code snippet demonstrates the setup phase for integration tests, where mock data is inserted into MongoDB collections. It ensures that the necessary `EventAggregator` and `IncidentsEvent` data are available before test execution. ```javascript before(async () => { // Insert mock data into MongoDB collections await EventAggregator.findOneAndUpdate(/* DMS data */); await IncidentsEvent.findOneAndUpdate(/* Incident data */); await IncidentsEvent.findOneAndUpdate(/* Flood data */); await IncidentsEvent.findOneAndUpdate(/* Closure data */); }); ``` -------------------------------- ### Integrate ParkMobile Config with Slack Notification Service in JavaScript Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parkmobile.md Shows how to use the ParkMobile configuration's Slack channel to send messages via a `slackService`, typically for alerts or notifications, demonstrating a practical application of the loaded configuration. ```javascript const parkmobileConfig = require('./config/vendor/parkmobile'); const slackService = require('../services/slack'); // Send alert to configured channel await slackService.sendMessage({ channel: parkmobileConfig.slackChannel, message: 'ParkMobile API error detected' }); ``` -------------------------------- ### Example InfluxDB Line Protocol Data Point Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database/influx.md Presents an example of a data point formatted in InfluxDB Line Protocol, which is the text-based format for writing data to InfluxDB. It shows the measurement name, tags (service, datacenter), a field (response_time), and a timestamp. ```text vendor_latency,service=tsp-api,datacenter=us-west-2 response_time=245.6 1640995200000000000 ``` -------------------------------- ### Example of Successfully Loaded Vendor Configuration Object Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor.md This JavaScript object represents the structure of the `module.exports` when all environment variables are correctly set and configurations are successfully loaded. It shows nested objects for each vendor, containing their respective settings like API keys, regions, and bucket names, ready for service consumption. ```javascript { aws: { region: 'us-west-2', sqs: { queueUrl: 'https://...' }, s3: { bucketName: 'my-bucket' } }, google: { maps: { apiKey: 'AIza...', url: 'https://maps.googleapis.com' } }, stripe: { secretKey: 'sk_live_...', webhookSecret: 'whsec_...' }, // ... other vendor configs } ``` -------------------------------- ### Setup and Teardown for Test Stubs Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/test-region-code.js.md Implements `beforeEach` and `afterEach` hooks for test setup and cleanup. It stubs the logger's error method before each test to capture error logs and restores it after each test to prevent interference with other tests. ```javascript beforeEach(() => { loggerErrorStub = sinon.stub(logger, 'error'); }); afterEach(() => { loggerErrorStub.restore(); }); ``` -------------------------------- ### Bash Commands to Test ParkMobile Environment Variable Overrides Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/parkmobile.md Provides bash commands to demonstrate how environment variables affect the loaded ParkMobile configuration, showing scenarios with no variables set and partial overrides for testing purposes. ```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' } ``` -------------------------------- ### HERE Routing API Mock Response Example Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-incident-event.md An example of a mock JSON response structure simulating the output from the HERE Routing API. This mock is used internally for route calculation to detect intersections with events, providing a simplified representation of routing data. ```javascript { routes: [ { sections: [ { summary: { baseDuration: 1 } } ] } ] } ``` -------------------------------- ### APIDOC: GET /getReservations API Endpoint Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test-reservation-uis-alert.js.md Documents the `getReservations` API endpoint, a GET method that retrieves a list of reservations. The response is enhanced to include an `is_uis_alert` boolean flag for each reservation, indicating whether any of its associated routes are affected by active transit alerts. ```APIDOC Endpoint: /getReservations Method: GET Response Enhancement: Adds 'is_uis_alert' boolean to each reservation object. Logic: Checks if reservation's routes have active alerts. ``` -------------------------------- ### API Endpoint: Get Suggestion Card by ID Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/test-suggestion-card.js.md Documents the GET /suggestion_card/{id} API endpoint for retrieving a specific suggestion card. It details the expected successful response structure, properties, and common error conditions for this operation. ```APIDOC GET /suggestion_card/{id} Successful Response Properties: notification_type: 12 (suggestion card type) points: Reward points associated with card status: Current card status (1 = active) Error Cases: 10003: Authentication Error (Missing Authorization header, returns "Token required") 23027: Card Not Found (Invalid card ID, returns "Not found card") ``` -------------------------------- ### JavaScript Basic Configuration Loading Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/default.md Demonstrates how to import and access configuration settings in a JavaScript application, specifically showing how to retrieve the application port from the loaded configuration object. ```javascript const config = require('./config/default.js'); console.log(`Starting on port: ${config.app.port}`); ``` -------------------------------- ### Example Test for MongoDB Reservation Service with Mocks Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/test/mocks/database.md This JavaScript snippet provides an example of testing a service that interacts with a MongoDB collection. It demonstrates how to set a mock return value for `mongo.db.collection().find().toArray()` and assert the service's output against the mocked data. ```javascript describe('Reservation Service', () => { it('should query reservations', async () => { const mockResult = [{ _id: '123', userId: 456 }]; mongo.db.collection().find().toArray.resolves(mockResult); const result = await reservationService.findAll(); expect(result).toEqual(mockResult); }); }); ``` -------------------------------- ### Examples of MongoDB Database Operation Results Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/database/mongo.md This snippet provides examples of common return values from MongoDB database operations. It includes the result format for an `insertOne` operation, an array of documents returned from a `find` operation, and an object showing counts from aggregation or count operations. ```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 } ``` -------------------------------- ### Integrating HERE Maps Configuration Module (JavaScript) Source: https://github.com/howard-metropia/knowledge-cs-tsp-api/blob/master/config/vendor/here.md This JavaScript example demonstrates the basic integration of the HERE Maps configuration module. It shows how to `require` the configuration and then use the extracted `apiKey` to initialize a hypothetical `HereSDK` instance, enabling access to HERE Maps services within the application. ```javascript const hereConfig = require('./config/vendor/here'); const hereSDK = new HereSDK(hereConfig.apiKey); ```