-
Notifications
You must be signed in to change notification settings - Fork 17
Functions
/src/app.ts
The whole server starts with the app.ts. Functions present:
-
main: The main function is the entry point of whole application. It calls the 3 child functions:
-
loadConfig: This function will load all the configurations from the default.yaml file to the environment of the whole application.
-
connectToDb: This function will initialize the connection of the mongo dB to the server using the mongoDb native driver.
-
initializeExpress: This function will initialize the whole express application with all the routes and middle wares. Tasks performed by this function: • Implements Express.json middleware for the request body creation and raw body creation in the string format. • Implements API Requests logger middleware. • Implements all the protocol routes. • Implements error handler function. • Spins up the whole server on the provided port number.
Controllers /src/controllers/actionHandlers.ts
This controller file consists of all the functions required to handle the requests for different actions. Functions present:
- unConfiguredActionHandler: This function is responsible for handling the requests for all the actions which are not configured on the protocol server. It will return those requests with 500 as http status code, with a message NACK, and error code as 4001.
/src/controllers/bap.protocol.ts
This controller file consists of all the functions required to handle all bap protocol requests which are responses from the network for the triggered requests.
- bapProtocolHandler: This function will handle all the on_action webhook calls. Tasks performed by this function: • Sends the acknowledgement response. • Cache the responses in case of search. • Makes call to the client with the response. • Handles errors and makes a call to the client with error data if there is any error.
/src/controllers/bap.trigger.ts
This controller file consists of all the functions required to handle all the bap trigger requests.
- triggerHandler: This function will handle all the configured action triggers. Tasks performed by this function: • Checks for each action whether it’s a search or not. In case if it’s not checks for the bpp_id and bpp_uri. Sends the acknowledgement based on that. • If the above conditions are met properly then it will send the acknowledgement with 202 status code. • Checks for useCache in the response body and action type for search, if it matches it caches the request. • Creates authorization header for the network calls. • Registry lookup and network based on the provided info with context. In case the bpp_id or bpp_uri provided it makes a direct call to the bpp. Else goes for broadcast. Looks up in the registry and makes a call to the network (it only happens in case of search.). • In case all calls to network failed, makes call to client with error. • Handles error, in case of errors between the procedure, makes call to client with the error.
/src/controllers/bpp.protocol.ts
This controller file consists of all the functions required to handle all the bpp requests and bpp response callbacks. Functions Present:
- bppProtocolHandler: All the requests from the network coming to BPP will be handled in this function. Tasks performed by this function: • Respond to the network with status code 202 in case the auth and json body is valid as per the schema. • In case of search the requests could come from the network or from a BAP directly. o If the search is coming through the gateway, then it will save the search type to be as broadcast and it’s auth Header with the transaction id. o If the search is coming from BAP, then it will save the search type to be as direct with its transaction id.
• Makes call to the provider application with request body. • Handles Error and provides the error to the provider application.
- publishResults: Once the provider application is done with process, it makes call to the on_action route of the protocol server and this controller handles all those requests. Tasks performed by this controller: • Inserts the bpp_id, bpp_uri and ttl for the response. • Sends back the acknowledgement to the provider application in case the auth is valid and JSON body is as per the schema. • Creates authorization for making calls to the network. • In case of search, as there could be types of searches so, this controller checks the database for the transaction id associated with the context of the request body. With data from the database, it sends the responses back to the gateway in case it’s a broadcast search, else it will send it back to the BAP directly. • Handles error and sends back to the provider application.
Middleware /src/middlewares/auth.ts
This file has all the middlewares required for authentication. Functions present:
- auth: This function will verify authorization header by checking the signature present inside the authorization header. Tasks performed by this function: • Check the config to verify whether to do the authorization check or not. • Does the verification of both Auth header, as proxy auth header (in case if its present.). • Sends 401 in case the verification fails. • Handles the error and sends request to the error handler function.
- authCreator: As the schema validator will validate the whole request without the auth header as invalid, we need to provide auth with the incoming requests in case of triggers (when the protocol server is configured as BAP) and for the requests from the provider application to the protocol server in BPP mode. Tasks provided by this middleware: • Creates authorization header. • Inserts in the headers of the incoming request.
/src/middlewares/context.ts
This file has the middleware required for context creation. Functions Present:
- contextMiddleware: This function creates the context object in case of triggers (when the protocol server is configured as BAP). Tasks performed by this function: • Creates the context using the build context function with the context object present in the request body. • Inserts this context in the request body as context object. • Handles error, sends the error to the error handler function.
/src/middlewares/jsonConverter.ts
This file has the middleware to convert the req body back into the raw request body. Functions Present:
- jsonConverter: As during the signature we need to use the request body without the tabs and spaces. So, in order to do that we are assigning the raw body into the request body. Tasks performed by this function: • Converts the raw body into JSON. • Assign it to the request body.
/src/middlewares/validator.ts
This file has the Open API Validator configured as the middleware for the schema validation. Functions Present:
- validator: validates the requests as per the provided open API schema file. Tasks performed by this function: • Validates the JSON body of the incoming request as per the provided open API schema file. • In case the JSON body of the incoming request is invalid then it will throw the error with the respective error codes. • The error handler function then sends the error as per the error status codes and the error message.
Routes /src/routes/protocol.ts
This file consists of a router which handles all the routes. Routes Present:
- Action Routes: All the action routes are configured as per the configuration file. Specifications: • All the actions which are present in the config file are handled by the respective handler. The unconfigured actions are handled by the unConfiguredActionHandler controller.
• BAP Mode:
o All the triggers need to go through a sequence of middlewares described below:
jsonConverter: converts and assigns raw body to request body.
authCreator: creates temporary auth header which is required to validate the JSON body of the incoming trigger request.
contextMiddleware: creates complete context object for the incoming request body.
validator: validates the request body as per the provided Open API schema.
o After passing through all these middlewares the request goes to triggerHandler.
o All the response webhooks (i.e., on_action routes) need to go through a sequence of middlewares described below: jsonConverter: convert and assign raw body to request body. validator: validates the request body as per the provided Open API schema. auth: Verifies the auth header and proxy auth header (in case it’s present) and passes the request forward in case it’s verified. o After passing through all these middlewares the request goes to bapProtocolHandler.
• BPP Mode: o All the action requests need to go through a sequence of middlewares described below: jsonConverter: converts and assigns raw body to request body. validator: validates the request body as per the provided Open API schema. auth: Verifies the auth header and proxy auth header (in case it’s present) and passes the request forward in case it’s verified. o After passing through all these middlewares the request goes to bppProtocolHandler.
o All the response callbacks from the provider application need to go through a sequence of middlewares described below: jsonConverter: converts and assigns raw body to request body. authCreator: creates temporary auth header which is required to validate the JSON body of the incoming trigger request. validator: validates the request body as per the provided Open API schema. o After passing through all these middlewares the request goes to publishResults controller.
- Cache Routes: As cache, requires need to be cleaned in order to optimize space. Routes Present for cache: a. Lookup cache route: This will erase all the cache data present in the lookupCache collection.
b. Response cache route: This will erase all the cache data present in the Response Cache collection.
Schemas /src/schemas/becknResponse.schema.ts
This file consists of the becknResponseSchema and BecknResponse type. • becknResponseSchema: This schema will be used to validate the request received by making calls to the network. • BecknResponse Type: This the type of data returned by the makeBecknRequet function.
/src/schemas/lookupParameter.schema.ts
This file consists of the lookupParametSchema and LookupParameter type. • lookupParametSchema: This schema will be used to validate the parameters provided for lookup in the registry. • LookupParameter Type: This is the type of data that needs to be passed in order to do a lookup using registryLookup function.
/src/schemas/ subscriberDetails.schema.ts
This file consists of the subscriberDetailsSchema and SubscriberDetails type. • subscriberDetailsSchema: This schema will be used to validate the details provided from the network about the subscriber present in the network. • SubscriberDetails Type: This is data type for Subcriber Detail present in the network.
Utils /src/utils/ auth.ts
This file consists of all the functions required for the authorization. Functions present:
-
ceateAuthHeaderConfig: Used to create Authorization headers using another function and return the formatted JSON for axios config. Functions used: • createAuthorizationHeader Input: • requestBody = The request body that has to be made to the Beckn network Used In: • authCreator Returns: • axios_config with Auth Header
-
createAuthorizationHeader: Takes in the raw message and then generates Blake-512 hash, adds created and expires timestamp, formats as per the specs and generates a signature using ED25519 private key and returns the signature. Functions used: • createSigningString Input: • message Used In: • createAuthHeaderConfig Returns: • Signature
-
createSigningString: Takes in the string format of the request body. Creates current time and expiry. Creates a hash of length 64. Combines the generated data and returns the signing string. Input • message Used In • createAuthorizationHeader Returns • signingString
-
verifyHeader: This function takes the header string as input. It obtains the subscriber ID and Unique Key ID and fetches the subscriber details ( i.e. public key of the subscriber whose auth needs to be verified) from the registry. This public key is then sent to createSigningString function to generate a signing string using which we verify if the signing string is valid. Functions used • getSubscriberDetails • verifyMessage • createSigningString Input • header Used In • auth Returns • Boolean
/src/utils/ becknRequester.ts
This file consists of each function required for making calls to the Beckn network. Functions Present:
-
makeBecknRequest: This function will make requests to the network based on the subscriber URL provided. Tasks performed by this function: • Takes subscriber URL, request body, headers, retry count and action. • Then creates the request URL by combining the subscriber URL and action. • Make POST requests to the request URL with request body, headers. • In case the request is successful it will return the data and status. • In case any error occurs or the requests fails with error status code, then it will retry for retry count times. • In case all the requests fail, it will return a response with status code 500.
-
callNetwork: This function will iteratively make requests to all the subscribers until one of the calls succeeds. Tasks performed by this function: • Takes a list of subscribers, request Body, headers and action as input. • Checks whether the list is empty or not, if it is empty, it will return response with status code 500. • In case it is not empty it will iteratively make requests using makeBecknRequest function until one of the calls succeeds. • It will return the response of success call. • In case all calls fail it will return the response with status code 500.
/src/utils/callbacks.ts
This file consists of client callback function. Functions Present:
- clientCallback: This function will send callback to the client application with data. Tasks Performed by this function: • Takes requestBody and isError flag as input. • Checks whether isError is true or false. • Make request to the client callback URL. • Handles error.
/src/utils/config.ts
This file consists of all configuration functions: Function Present:
-
loadConfigs: This function will load all the configs from the default.yaml file to the application environment. Tasks performed by this function: • Imports all the configurations from default.yaml file to the environment.
-
getConfiguredActions: This function helps in getting the list of configured actions as per the default.yaml config file. Tasks performed by this function: • Returns a list of configured actions.
/src/utils/context.ts
This file consists of all functions required for the context. Functions Present:
- buildContext: This function will build a proper context object for the request body. Tasks performed by this function: • Checks whether the context object is defined with domain or not. • Provides the country field value in case not present. • Provides the city field value in case not present. • Checks for the useCache field. • Provides a newly generated transaction id in case not present. • Generates new message id. • Add ttl to the context body. • Add timestamp. • Adds bap_id and bap_uri as per the configuration. • Adds action field as per the action call.
/src/utils/lookup.cache.ts
This file consists of all functions required for the lookup cache. Functions Present:
-
createExpireIndex: This function will create an expire index so that the lookup cache data should automatically be deleted from the database. Tasks performed by this function: • Creates expire index, which will help database erase the whole document at time expiresAt.
-
createQuery: This function will create a query for the cache. Tasks performed by this function: • Creates a query object from the lookup parameters. • Provides a placeholder value in case some parameter is undefined. • Returns the query object.
-
cache: This function will save the cache data on the database. Tasks performed by this function: • Fetches the lookup cache collection. • Creates expire index using the createExpireIndex function. • Creates query object using the createQuery function. • Generates the expiration date considering the valid until date of each subscriber and lookup cache TTL. • Saves the data in the database with query object, subscribers and expiration date.
-
check: This function will check for cache and return if it is present. Tasks performed by this function: • Fetches the lookup cache collection. • Creates query object using the createQuery function. • Fetches the data from the database using the query object. • If it is present, it returns the list of subscribers or else returns null.
-
clear: This function will clear the whole cache from the database. Tasks performed by this function: • Fetches the lookup cache collection. • Deletes all the documents inside the collection.
/src/utils/lookup.ts
This file consists of all the functions required for lookup. Functions Present:
- registryLookup: This function looks up the registry for subscribers. Tasks performed by this function: • Takes lookup parameter object as input • Check the cache, in case present returns the list of subscribers from cache. • If not present in the cache, then make a POST request to the registry URL, with lookup parameters. • Parses the received list of subscribers to validate and remove the invalid entry. • Caches the result for future use. • Returns the list of subscribers.
- getSubscriberDetails: This function looks up the registry for a particular subscriber. Tasks performed by this function: • Takes subscriber id and unique key id as input. • Uses the registryLookup function for getting the subscribers. • Checks the length of subscribers, in case zero throws error. • Returns the first valid subscriber.
/src/utils/response.Cache.ts
This file will consist of all the functions required for response caching. Functions present:
-
createExpireIndex: This function will create an expire index so that the lookup cache data should automatically be deleted from the database. Tasks performed by this function: • Creates expire index, which will help database erase the whole document at time expiresAt.
-
createParameters: This function will create parameters for response caching and retrieval. Tasks performed by this function: • Takes requestBody as input. • Creates a params object with domain, country, city, action and core version from context object and the whole message body. • Returns the params object.
-
cacheRequest: This function will cache the request to track and cache the responses for this request. Tasks performed by this function: • Fetches the response cache collection. • Creates expire index using the createExpireIndex function. • Creates parameter object using the createParameters function. • Saves the data with requestBody, transaction id, expiration date and parameters.
- cacheResponse: This function will cache the response. Tasks performed by this function: • Fetches the response cache collection. • Creates expire index using the createExpireIndex function. • Creates parameter object using the createParameters function. • Creates expiration date as per the TTL of response. • Updates the data already saved with request.
- check: This function will check for the cache and returns in case found. Tasks performed by this function: • Fetches the response cache collection. • Creates parameter object using the createParameters function. • Searches the database using the parameter object created before. • Returns the array of responses in case found, else returns null.
- clear: This function will clear the whole cache from the database. Tasks performed by this function: • Fetches the lookup cache collection. • Deletes all the documents inside the collection.