Skip to content

Commit

Permalink
[main] - did the update local function
Browse files Browse the repository at this point in the history
  • Loading branch information
iosifv committed May 19, 2024
1 parent 37d3790 commit bb2120a
Show file tree
Hide file tree
Showing 16 changed files with 219 additions and 64 deletions.
9 changes: 8 additions & 1 deletion sls-api/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,11 @@ yarn-error.log
.esbuild

# environment files
.env
.env

# json mock files
src/functions/authentication/mock.json
src/functions/direction/mock.json
src/functions/healthcheck/mock.json
src/functions/location/mock.json
src/functions/statistics/mock.json
5 changes: 3 additions & 2 deletions sls-api/package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
{
"name": "clip-sls-api",
"version": "1.0.0",
"version": "1.1.0",
"author": "Iosifv",
"description": "Serverless aws-nodejs-typescript app for the cli-path application",
"main": "serverless.ts",
"scripts": {
"update-auth0-token": "node update-auth0-token.js",
"invoke-local-01-health": "sls invoke local --function=healthcheck --path=src/functions/healthcheck/mock.json",
"invoke-local-02-auth": "sls invoke local --function=authentication --path=src/functions/authentication/mock.json",
"invoke-local-03-location": "sls invoke local --function=location --path=src/functions/location/mock.json",
Expand Down Expand Up @@ -41,6 +43,5 @@
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.3"
},
"author": "The serverless webpack authors (https://github.com/elastic-coders/serverless-webpack)",
"license": "MIT"
}
5 changes: 2 additions & 3 deletions sls-api/src/functions/authentication/mock.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9pb3NpZnYuZXUuYXV0aDAuY29tLyJ9..OdkeuJJdkwkc60Y9.ENmMJVqfBkPsPKWw6bgi5Hbv-VHDNq0j8b2gZmksoNp3xKstpqzei5qLsk7_uQTLTKCnV4YlbEsetxG584Datrjoqo_uC1pGSEnkjlpezo7bgmBSnF6shaI4AwbJ3ooSV2wuoFZRYDSrvjS-SQzSQDIv8VuS2qCMY0s-nDOiKkUKXdUDzZIa9wCiNxqT1Wn112p3IgTIueFnePZTjm0BGJkICsv2gDph867QZV0CfvhvV0kTtXBpgLaPHKpEbMM2_MmF06bEN_fGwi_hH6hQYA.7b6ZDoHPVvP0OxLdGt5DvQ"
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"payload\": \"empty\"}"
}

}
7 changes: 7 additions & 0 deletions sls-api/src/functions/authentication/mock.json.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"payload\": \"empty\"}"
}
35 changes: 17 additions & 18 deletions sls-api/src/functions/direction/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,33 @@ import { middyfy } from '@libs/lambda'
import { canPrefetch, getInternal, processCache } from '@middy/util'
import { Client } from '@googlemaps/google-maps-services-js'
import * as dotenv from 'dotenv'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb'
// import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
// import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb'

import schema from './schema'
import { TABLE_NAME_USAGE_LOG } from '@utils/constants'

dotenv.config()
const dynamoDbClient = new DynamoDBClient()
const dynamoDbDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)
// const dynamoDbDocumentClient = DynamoDBDocumentClient.from(new DynamoDBClient())

const direction: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => {
const client = new Client({})

const timestamp = new Date().toISOString() // Convert Date to ISO string
const params = {
TableName: TABLE_NAME_USAGE_LOG,
Item: {
CreatedAt: timestamp,
User: event.user.nickname,
Data: event.body,
},
}
// const timestamp = new Date().toISOString() // Convert Date to ISO string
// const params = {
// TableName: TABLE_NAME_USAGE_LOG,
// Item: {
// CreatedAt: timestamp,
// User: event.user.nickname,
// Data: event.body,
// },
// }

try {
await dynamoDbDocumentClient.send(new PutCommand(params))
} catch (error) {
console.log(error)
}
// try {
// await dynamoDbDocumentClient.send(new PutCommand(params))
// } catch (error) {
// console.log(error)
// }

return await client
.directions({
Expand Down
5 changes: 2 additions & 3 deletions sls-api/src/functions/direction/mock.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9pb3NpZnYuZXUuYXV0aDAuY29tLyJ9..NY-9HQYiM8YidKN-.ZW1vgY3HFABgf8j7tU7kRB-UvG2E6XNbzMCTevX3W8HCLXetz5ZgdliOEsDioC0oZR9ZhjJ92lCR0FzKgD2ZZ0tPd_ymqmQeHvvk1Bbq7lVZncTAVGhtqZdIACzbisOupCDYlZa_1YzN1nelBfjIPLYSlfLFRQmdyCDCN-VvR5DcpvoYXrCnpte3xSHVyBZOrUm2_F0IxiaDxMfnpzQZJyIBB6Nyep3LAOA5hOGHNIZA5ft80EbhLUp07qsbSF9pGU4WpXKmhwenr_oc1TEP-w.XPPQRq2Vl3J67JAjsRuHNA"

"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"origin\": \"Amsterdam\",\"destination\": \"Berlin\"}"
}
}
7 changes: 7 additions & 0 deletions sls-api/src/functions/direction/mock.json.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"origin\": \"Amsterdam\",\"destination\": \"Berlin\"}"
}
4 changes: 2 additions & 2 deletions sls-api/src/functions/healthcheck/mock.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9pb3NpZnYuZXUuYXV0aDAuY29tLyJ9..OdkeuJJdkwkc60Y9.ENmMJVqfBkPsPKWw6bgi5Hbv-VHDNq0j8b2gZmksoNp3xKstpqzei5qLsk7_uQTLTKCnV4YlbEsetxG584Datrjoqo_uC1pGSEnkjlpezo7bgmBSnF6shaI4AwbJ3ooSV2wuoFZRYDSrvjS-SQzSQDIv8VuS2qCMY0s-nDOiKkUKXdUDzZIa9wCiNxqT1Wn112p3IgTIueFnePZTjm0BGJkICsv2gDph867QZV0CfvhvV0kTtXBpgLaPHKpEbMM2_MmF06bEN_fGwi_hH6hQYA.7b6ZDoHPVvP0OxLdGt5DvQ"
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"name\": \"Iosif\"}"
}
}
7 changes: 7 additions & 0 deletions sls-api/src/functions/healthcheck/mock.json.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"name\": \"Iosif\"}"
}
4 changes: 2 additions & 2 deletions sls-api/src/functions/location/mock.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9pb3NpZnYuZXUuYXV0aDAuY29tLyJ9..OdkeuJJdkwkc60Y9.ENmMJVqfBkPsPKWw6bgi5Hbv-VHDNq0j8b2gZmksoNp3xKstpqzei5qLsk7_uQTLTKCnV4YlbEsetxG584Datrjoqo_uC1pGSEnkjlpezo7bgmBSnF6shaI4AwbJ3ooSV2wuoFZRYDSrvjS-SQzSQDIv8VuS2qCMY0s-nDOiKkUKXdUDzZIa9wCiNxqT1Wn112p3IgTIueFnePZTjm0BGJkICsv2gDph867QZV0CfvhvV0kTtXBpgLaPHKpEbMM2_MmF06bEN_fGwi_hH6hQYA.7b6ZDoHPVvP0OxLdGt5DvQ"
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"query\": \"Dam Square Ams\"}"
}
}
7 changes: 7 additions & 0 deletions sls-api/src/functions/location/mock.json.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"query\": \"Dam Square Ams\"}"
}
5 changes: 2 additions & 3 deletions sls-api/src/functions/statistics/mock.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9pb3NpZnYuZXUuYXV0aDAuY29tLyJ9.._olX-PXcTyZ2IrCG.2pt3kxAUemOXZf0KbkHxDnDswMk75Pgj5ewP_ig0faHy_Kxc0OvNQg8gdmSLlDweQpos9kyPS612C2hHvf5AvrtQh3s2J4aFDGnOoJ8ozymFtTa4m12qwimpK31DyGYno_SJ89wL12pdcQ71eB-N3K5RjDZbg07UGymGs_bXFSVmv929MX_U0XiVBSIJenOnuXg9cyArkDgJa4E5nDkmrf3fVMwJRI3F7-2bL41Upyaycd5fmpJ-HUbwt3vfgBqXO9ncuEIWQMt3J6-u5dv3nw.RKB1-pYhLxZCQL-CWKyfmg"
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"payload\": \"empty\"}"
}

}
7 changes: 7 additions & 0 deletions sls-api/src/functions/statistics/mock.json.bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer the_token_goes_here"
},
"body": "{\"payload\": \"empty\"}"
}
58 changes: 58 additions & 0 deletions sls-api/src/libs/call-counter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb'
import { TABLE_NAME_USAGE_LOG } from '@utils/constants'
import {} from '@aws-sdk/lib-dynamodb'

// const dynamoDbClient = new DynamoDBClient()
// const dynamoDbDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)

async function getMonthlyCount(): Promise<number> {
const dynamoDbDocumentClient = DynamoDBDocumentClient.from(new DynamoDBClient())
const currentDate = new Date()
const currentMonth = currentDate.getMonth() + 1 // Months are 0-based, so adding 1
const currentYear = currentDate.getFullYear()
let beginFilter: string
if (currentMonth < 10) {
beginFilter = `${currentYear}-0${currentMonth}`
} else {
beginFilter = `${currentYear}-${currentMonth}`
}

const params = {
TableName: TABLE_NAME_USAGE_LOG,
FilterExpression: 'begins_with(CreatedAt, :prefix)',
ExpressionAttributeValues: {
':prefix': { S: beginFilter },
},
}

try {
const data = await dynamoDbDocumentClient.send(new ScanCommand(params))
return data.Count || 0 // Return 0 if Count is undefined
} catch (error) {
console.error('Unable to scan the table. Error:', error)
return 0 // Return 0 if there's an error
}
}

async function increaseMonthlyCount(event) {
const dynamoDbDocumentClient = DynamoDBDocumentClient.from(new DynamoDBClient())
const timestamp = new Date().toISOString() // Convert Date to ISO string
const params = {
TableName: TABLE_NAME_USAGE_LOG,
Item: {
CreatedAt: timestamp,
User: event.user.nickname,
Data: event.body,
},
}

try {
await dynamoDbDocumentClient.send(new PutCommand(params))
} catch (error) {
console.log(error)
}
}

export default getMonthlyCount
increaseMonthlyCount
61 changes: 31 additions & 30 deletions sls-api/src/libs/my-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,44 @@ import middy from '@middy/core'
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'
import { Auth0Client } from '@libs/client-auth0'
import { formatJSONError } from './api-gateway'
import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'
import getMonthlyCount from './call-counter'
// import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb'
// import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'
import {
MAXIMUM_ALLOWED_MONTHLY_GOOGLE_DIRECTION_CALLS,
TABLE_NAME_USAGE_LOG,
// TABLE_NAME_USAGE_LOG,
} from '@utils/constants'

const dynamoDbClient = new DynamoDBClient()
const dynamoDbDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)
// const dynamoDbClient = new DynamoDBClient()
// const dynamoDbDocumentClient = DynamoDBDocumentClient.from(dynamoDbClient)

async function getMonthlyCount(): Promise<number> {
const currentDate = new Date()
const currentMonth = currentDate.getMonth() + 1 // Months are 0-based, so adding 1
const currentYear = currentDate.getFullYear()
let beginFilter: string
if (currentMonth < 10) {
beginFilter = `${currentYear}-0${currentMonth}`
} else {
beginFilter = `${currentYear}-${currentMonth}`
}
// async function getMonthlyCount(): Promise<number> {
// const currentDate = new Date()
// const currentMonth = currentDate.getMonth() + 1 // Months are 0-based, so adding 1
// const currentYear = currentDate.getFullYear()
// let beginFilter: string
// if (currentMonth < 10) {
// beginFilter = `${currentYear}-0${currentMonth}`
// } else {
// beginFilter = `${currentYear}-${currentMonth}`
// }

const params = {
TableName: TABLE_NAME_USAGE_LOG,
FilterExpression: 'begins_with(CreatedAt, :prefix)',
ExpressionAttributeValues: {
':prefix': { S: beginFilter },
},
}
// const params = {
// TableName: TABLE_NAME_USAGE_LOG,
// FilterExpression: 'begins_with(CreatedAt, :prefix)',
// ExpressionAttributeValues: {
// ':prefix': { S: beginFilter },
// },
// }

try {
const data = await dynamoDbDocumentClient.send(new ScanCommand(params))
return data.Count || 0 // Return 0 if Count is undefined
} catch (error) {
console.error('Unable to scan the table. Error:', error)
return 0 // Return 0 if there's an error
}
}
// try {
// const data = await dynamoDbDocumentClient.send(new ScanCommand(params))
// return data.Count || 0 // Return 0 if Count is undefined
// } catch (error) {
// console.error('Unable to scan the table. Error:', error)
// return 0 // Return 0 if there's an error
// }
// }

const myMiddleware = (): middy.MiddlewareObj<APIGatewayProxyEvent> => {
let authResponse
Expand Down
57 changes: 57 additions & 0 deletions sls-api/update-auth0-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const fs = require('fs')
const path = require('path')
require('dotenv').config()

// List of paths to the mock.json files
const filePaths = [
path.join(__dirname, 'src/functions/authentication/mock.json'),
path.join(__dirname, 'src/functions/direction/mock.json'),
path.join(__dirname, 'src/functions/healthcheck/mock.json'),
path.join(__dirname, 'src/functions/location/mock.json'),
path.join(__dirname, 'src/functions/statistics/mock.json'),
]

// Retrieve the new token from the CLI argument or .env file
const newToken = process.argv[2] || process.env.AUTH0_TOKEN

if (!newToken) {
console.error('AUTH0_TOKEN is not defined in the .env file')
process.exit(1)
}

const authorizationHeaderValue = 'Bearer ' + newToken

// Function to update a single mock.json file
const updateAuthorizationToken = (filePath) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file at ${filePath}:`, err)
return
}

try {
// Parse the JSON data
const jsonData = JSON.parse(data)

// Update the Authorization key with the new token
jsonData.headers.Authorization = authorizationHeaderValue

// Convert the JSON object back to a string
const updatedJsonData = JSON.stringify(jsonData, null, 2)

// Write the updated JSON back to the file
fs.writeFile(filePath, updatedJsonData, 'utf8', (err) => {
if (err) {
console.error(`Error writing file at ${filePath}:`, err)
} else {
console.log(`Authorization token updated successfully in ${filePath}`)
}
})
} catch (parseError) {
console.error(`Error parsing JSON in file at ${filePath}:`, parseError)
}
})
}

// Iterate over each file path and update the authorization token
filePaths.forEach(updateAuthorizationToken)

0 comments on commit bb2120a

Please sign in to comment.