-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds support for typescript #10
Open
KellyBennett
wants to merge
2
commits into
PlayFab:main
Choose a base branch
from
KellyBennett:typescript_support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+5,922
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
*.js.map | ||
*.ts | ||
.git* | ||
.vscode | ||
local.settings.json | ||
test |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
bin | ||
obj | ||
csx | ||
.vs | ||
edge | ||
Publish | ||
|
||
*.user | ||
*.suo | ||
*.cscfg | ||
*.Cache | ||
project.lock.json | ||
|
||
/packages | ||
/TestResults | ||
|
||
/tools/NuGet.exe | ||
/App_Data | ||
/secrets | ||
/data | ||
.secrets | ||
appsettings.json | ||
local.settings.json | ||
|
||
node_modules | ||
dist | ||
|
||
# Local python packages | ||
.python_packages/ | ||
|
||
# Python Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"recommendations": [ | ||
"ms-azuretools.vscode-azurefunctions" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"name": "Debug Tests", // This is the configuration name you will see in debug sidebar | ||
"type": "pwa-node", | ||
"resolveSourceMapLocations": [ | ||
"${workspaceFolder}/**", | ||
"!**/node_modules/**" | ||
], | ||
"request": "launch", | ||
"runtimeArgs": [ | ||
"--inspect-brk", | ||
"${workspaceRoot}/node_modules/jest/bin/jest.js", // Path to Jest | ||
"--runInBand", | ||
"-i" | ||
], | ||
"console": "internalConsole", | ||
"internalConsoleOptions": "openOnSessionStart", | ||
"sourceMaps": true | ||
}, | ||
{ | ||
"name": "Attach to Node Functions", | ||
"type": "node", | ||
"request": "attach", | ||
"port": 9229, | ||
"preLaunchTask": "func: host start" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"azureFunctions.deploySubpath": ".", | ||
"azureFunctions.postDeployTask": "npm install", | ||
"azureFunctions.projectLanguage": "TypeScript", | ||
"azureFunctions.projectRuntime": "~3", | ||
"debug.internalConsoleOptions": "neverOpen", | ||
"azureFunctions.preDeployTask": "npm prune", | ||
"editor.codeActionsOnSave": { | ||
"source.fixAll": true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
{ | ||
"version": "2.0.0", | ||
"tasks": [ | ||
{ | ||
"type": "func", | ||
"command": "host start", | ||
"problemMatcher": "$func-node-watch", | ||
"isBackground": true, | ||
"dependsOn": "npm build" | ||
}, | ||
{ | ||
"type": "shell", | ||
"label": "npm build", | ||
"command": "npm run build", | ||
"dependsOn": "npm install", | ||
"problemMatcher": "$tsc" | ||
}, | ||
{ | ||
"type": "shell", | ||
"label": "npm install", | ||
"command": "npm install" | ||
}, | ||
{ | ||
"type": "shell", | ||
"label": "npm prune", | ||
"command": "npm prune --production", | ||
"dependsOn": "npm build", | ||
"problemMatcher": [] | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
{ | ||
"bindings": [ | ||
{ | ||
"authLevel": "function", | ||
"type": "httpTrigger", | ||
"route": "CloudScript/ExecuteFunction", | ||
"direction": "in", | ||
"name": "req", | ||
"methods": ["get", "post"] | ||
}, | ||
{ | ||
"type": "http", | ||
"direction": "out", | ||
"name": "res" | ||
} | ||
], | ||
"scriptFile": "../dist/ExecuteFunction/index.js" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,231 @@ | ||
import axios from 'axios'; | ||
import { gzip, ungzip } from 'node-gzip'; | ||
import functionToTest from './index'; | ||
|
||
const { runStubFunctionFromBindings, createHttpTrigger } = require('stub-azure-function-context'); | ||
|
||
// Mock response when fetching Profile from PlayFab | ||
const mockProfileSuccessResponse = { | ||
status: 200, | ||
statusText: 'OK', | ||
data: { | ||
code: 200, | ||
status: 'OK', | ||
data: { | ||
Profile: { | ||
Entity: { | ||
Id: '67BA331332AF6263', | ||
Type: 'title_player_account', | ||
TypeString: 'title_player_account', | ||
}, | ||
EntityChain: 'title_player_account!BDA2F45267E09A44/ALSLF/D99A2D9D9E5FDD94/67BCE31312AF6263/', | ||
VersionNumber: 0, | ||
Lineage: { | ||
NamespaceId: 'BDA2F96667E09A44', | ||
TitleId: 'asdfas', | ||
MasterPlayerAccountId: 'D99A2ASD9E5FDD94', | ||
TitlePlayerAccountId: '67BCE3131SFE263', | ||
}, | ||
Created: '2020-12-08T19:19:53.37Z', | ||
}, | ||
}, | ||
}, | ||
}; | ||
|
||
const mockProfileUnauthorizedResponse = { | ||
status: 200, | ||
statusText: 'OK', | ||
data: { | ||
code: 401, | ||
status: 'Unauthorized', | ||
error: 'NotAuthenticated', | ||
errorCode: 1074, | ||
errorMessage: 'This API method does not allow anonymous callers.', | ||
}, | ||
}; | ||
|
||
// Mock response from your AzureFunction (the one refered to by FunctionName) | ||
const mockFunctionResponse = { | ||
status: 200, | ||
statusText: 'OK', | ||
data: {}, | ||
}; | ||
|
||
const defaultRequestBody = { | ||
FunctionName: 'RequestMatch', | ||
Entity: { | ||
Id: 'asldkf', | ||
Type: 'asdfasd', | ||
TypeString: 'asdfasldfj', | ||
}, | ||
}; | ||
|
||
const requestBodyWithoutEntity = { | ||
FunctionName: 'RequestMatch', | ||
}; | ||
|
||
const defaultHeaders = { | ||
'content-type': 'application/json; charset=utf-8', | ||
accept: '*/*', | ||
'accept-encoding': 'deflate, gzip', | ||
host: 'localhost:7071', | ||
'user-agent': 'Crimson/++UE4+Release-4.25-CL-0 Windows/10.0.18363.1.256.64bit', | ||
'content-length': '31', | ||
'x-playfabsdk': 'UE4MKPL-1.48.201014', | ||
'x-entitytoken': | ||
'M3x7ImkiOiIyMDIwLTEyLTA4VDAwOjMxOjAzLjMzMTIwMDhaIiwiaWRwIjoiQ3VzdG9tIiwiZSI6IjIwMjAtMTItMDlUMDA6MzE6MDMuMzMxMjAwOFoiLCJoIjoiMzI1NkUyMjI4MjVFQUNFNiIsInMiOiJjYWw3SzhKN3B1dUFleTNONjY2bXJ6Qk5zc1RnditDSHBKOHJGZ1FlbUw4PSIsImVjIjoidGl0bGVfcGxheWVyX2FjY291bnQhQkRBMkY5NjY2N0UwOUE0NC83RTNGQi8xOUVGMEMzQkQxNUMzMzQ3L0U4Q0Y2Qjg0RkQ2MEZBMDQvIiwiZWkiOiJFOENGNkI4NEZENjBGQTA0IiwiZXQiOiJ0aXRsFjfobow8ZXJfYWNjb3VudCJ9', | ||
}; | ||
|
||
const headersWithoutComrpression = { | ||
'content-type': 'application/json; charset=utf-8', | ||
accept: '*/*', | ||
host: 'localhost:7071', | ||
'user-agent': 'Crimson/++UE4+Release-4.25-CL-0 Windows/10.0.18363.1.256.64bit', | ||
'content-length': '31', | ||
'x-playfabsdk': 'UE4MKPL-1.48.201014', | ||
'x-entitytoken': | ||
'M3x7ImkiOiIyMDIwLTEyLTA4VDAwOjMxOjAzLjMzMTIwMDhaIiwiaWRwIjoiQ3VzdG9tIiwiZSI6IjIwMjAtMTItMDlUMDA6MzE6MDMuMzMxMjAwOFoiLCJoIjoiMzI1NkUyMjI4MjVFQUNFNiIsInMiOiJjYWw3SzhKN3B1dUFleTNONjY2bXJ6Qk5zc1RnditDSHBKOHJGZ1FlbUw4PSIsImVjIjoidGl0bGVfcGxheWVyX2FjY291bnQhQkRBMkY5NjY2N0UwOUE0NC83RTNGQi8xOUVGMEMzQkQxNUMzMzQ3L0U4Q0Y2Qjg0RkQ2MEZBMDQvIiwiZWkiOiJFOENGNkI4NEZENjBGQTA0IiwiZXQiOiJ0aXRsFjfobow8ZXJfYWNjb3VudCJ9', | ||
}; | ||
|
||
const headersWithoutEntityToken = { | ||
'content-type': 'application/json; charset=utf-8', | ||
accept: '*/*', | ||
'accept-encoding': 'deflate, gzip', | ||
host: 'localhost:7071', | ||
'user-agent': 'Crimson/++UE4+Release-4.25-CL-0 Windows/10.0.18363.1.256.64bit', | ||
'content-length': '31', | ||
'x-playfabsdk': 'UE4MKPL-1.48.201014', | ||
}; | ||
|
||
interface BootstrapParams { | ||
body?: object; | ||
headers?: object; | ||
} | ||
|
||
const bootstrappedFunction = async ({ body = defaultRequestBody, headers = defaultHeaders }: BootstrapParams = {}) => { | ||
return runStubFunctionFromBindings( | ||
functionToTest, | ||
[ | ||
{ | ||
type: 'httpTrigger', | ||
name: 'req', | ||
direction: 'in', | ||
data: createHttpTrigger('POST', 'http://localhost:7071/CloudScript/ExecuteFunction', headers, {}, body), | ||
}, | ||
{ type: 'http', name: 'res', direction: 'out' }, | ||
], | ||
new Date(), | ||
); | ||
}; | ||
|
||
describe('ExecuteFunction', () => { | ||
process.env.PLAYFAB_TITLE_ID = 'TESTID'; | ||
|
||
it('Responds successfully with valid params', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
const context = await bootstrappedFunction(); | ||
expect(context).toHaveProperty('res.status', 200); | ||
|
||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Calls playfab to fetch a profile', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
await bootstrappedFunction(); | ||
expect(mockedAxios).toHaveBeenCalledWith( | ||
'/Profile/GetProfile', | ||
{ Entity: { Id: 'asldkf', Type: 'asdfasd', TypeString: 'asdfasd' } }, | ||
{ | ||
baseURL: 'https://TESTID.playfabapi.com', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
'X-EntityToken': | ||
'M3x7ImkiOiIyMDIwLTEyLTA4VDAwOjMxOjAzLjMzMTIwMDhaIiwiaWRwIjoiQ3VzdG9tIiwiZSI6IjIwMjAtMTItMDlUMDA6MzE6MDMuMzMxMjAwOFoiLCJoIjoiMzI1NkUyMjI4MjVFQUNFNiIsInMiOiJjYWw3SzhKN3B1dUFleTNONjY2bXJ6Qk5zc1RnditDSHBKOHJGZ1FlbUw4PSIsImVjIjoidGl0bGVfcGxheWVyX2FjY291bnQhQkRBMkY5NjY2N0UwOUE0NC83RTNGQi8xOUVGMEMzQkQxNUMzMzQ3L0U4Q0Y2Qjg0RkQ2MEZBMDQvIiwiZWkiOiJFOENGNkI4NEZENjBGQTA0IiwiZXQiOiJ0aXRsFjfobow8ZXJfYWNjb3VudCJ9', | ||
}, | ||
}, | ||
); | ||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Calls local Azure Function', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
await bootstrappedFunction(); | ||
|
||
expect(mockedAxios).toHaveBeenCalledWith( | ||
'/api/RequestMatch', | ||
'{"TitleAuthenticationContext":{"Id":"TESTID","EntityToken":"M3x7ImkiOiIyMDIwLTEyLTA4VDAwOjMxOjAzLjMzMTIwMDhaIiwiaWRwIjoiQ3VzdG9tIiwiZSI6IjIwMjAtMTItMDlUMDA6MzE6MDMuMzMxMjAwOFoiLCJoIjoiMzI1NkUyMjI4MjVFQUNFNiIsInMiOiJjYWw3SzhKN3B1dUFleTNONjY2bXJ6Qk5zc1RnditDSHBKOHJGZ1FlbUw4PSIsImVjIjoidGl0bGVfcGxheWVyX2FjY291bnQhQkRBMkY5NjY2N0UwOUE0NC83RTNGQi8xOUVGMEMzQkQxNUMzMzQ3L0U4Q0Y2Qjg0RkQ2MEZBMDQvIiwiZWkiOiJFOENGNkI4NEZENjBGQTA0IiwiZXQiOiJ0aXRsFjfobow8ZXJfYWNjb3VudCJ9"},"CallerEntityProfile":{"Entity":{"Id":"67BA331332AF6263","Type":"title_player_account","TypeString":"title_player_account"},"EntityChain":"title_player_account!BDA2F45267E09A44/ALSLF/D99A2D9D9E5FDD94/67BCE31312AF6263/","VersionNumber":0,"Lineage":{"NamespaceId":"BDA2F96667E09A44","TitleId":"asdfas","MasterPlayerAccountId":"D99A2ASD9E5FDD94","TitlePlayerAccountId":"67BCE3131SFE263"},"Created":"2020-12-08T19:19:53.37Z"}}', | ||
{ baseURL: 'http://localhost:7071', headers: { 'Content-Type': 'application/json' } }, | ||
); | ||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Returns a gzipped response body', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
const response = await bootstrappedFunction(); | ||
expect(Buffer.isBuffer(response.res.body)).toBe(true); | ||
ungzip(response.res.body) | ||
.then((uncompressed) => { | ||
return gzip(uncompressed); | ||
}) | ||
.then((compressed) => { | ||
expect(compressed).toEqual(response.res.body); | ||
}); | ||
|
||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Respondes with a full "ExecuteFunctionResult"', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
const response = await bootstrappedFunction(); | ||
const unzippedResponseBody = await ungzip(response.res.body); | ||
const responseString = unzippedResponseBody.toString(); | ||
const responseBody = JSON.parse(responseString); | ||
expect(responseBody).toHaveProperty('data.ExecutionTimeMilliseconds'); | ||
expect(responseBody).toHaveProperty('data.FunctionName'); | ||
expect(responseBody).toHaveProperty('data.FunctionResult'); | ||
expect(responseBody).toHaveProperty('data.FunctionResultTooLarge'); | ||
|
||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Does not gzip the result if gzip header is not present', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
|
||
const response = await bootstrappedFunction({ headers: headersWithoutComrpression }); | ||
expect(Buffer.isBuffer(response.res.body)).toBe(true); | ||
expect(async () => { | ||
await ungzip(response.res.body); | ||
}) | ||
.rejects // https://stackoverflow.com/a/61214808 | ||
.toThrowError('Error: incorrect header check'); | ||
|
||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Returns a 401 when no Caller Entity Token header is present', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileUnauthorizedResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
const response = await bootstrappedFunction({ headers: headersWithoutEntityToken }); | ||
expect(response).toHaveProperty('res.status', 401); | ||
mockedAxios.mockRestore(); | ||
}); | ||
|
||
it('Returns a 200 when Entity is present in the request body', async () => { | ||
const mockedAxios = jest.spyOn(axios, 'post'); | ||
mockedAxios.mockResolvedValueOnce(mockProfileSuccessResponse).mockResolvedValueOnce(mockFunctionResponse); | ||
const response = await bootstrappedFunction({ body: requestBodyWithoutEntity }); | ||
expect(response).toHaveProperty('res.status', 200); | ||
mockedAxios.mockRestore(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,214 @@ | ||
// A local implementation of the ExecuteFunction feature. Provides the ability to execute an Azure Function with a local URL with respect to the host | ||
// of the application this function is running in. | ||
// <param name="httpRequest">The HTTP request</param> | ||
// <returns>The function execution result(s)</returns> | ||
import { AzureFunction, Context, HttpRequest } from "@azure/functions"; | ||
import axios from "axios"; | ||
import { gzip } from "node-gzip"; | ||
import { StopWatch } from "stopwatch-node"; | ||
import hostDotJson from "../host.json"; | ||
|
||
/* | ||
Types and Class definitions | ||
*/ | ||
class FunctionContextInternal { | ||
TitleAuthenticationContext: TitleAuthenticationContext; | ||
|
||
CallerEntityProfile: EntityProfile | undefined; | ||
|
||
FunctionArgument: JSON; | ||
|
||
constructor( | ||
TitleAuthenticationContext: TitleAuthenticationContext, | ||
CallerEntityProfile: EntityProfile | undefined, | ||
FunctionArgument: JSON | ||
) { | ||
this.TitleAuthenticationContext = TitleAuthenticationContext; | ||
this.CallerEntityProfile = CallerEntityProfile; | ||
this.FunctionArgument = FunctionArgument; | ||
} | ||
} | ||
|
||
type TitleAuthenticationContext = { | ||
Id: string; | ||
EntityToken: string; | ||
}; | ||
|
||
type EntityProfileResponse = { | ||
data: { | ||
Profile: EntityProfile; | ||
}; | ||
code: number; | ||
}; | ||
|
||
type EntityProfile = { | ||
Entity: Entity; | ||
Created: Date; | ||
EntityChain: string; | ||
Lineage: EntityLineage; | ||
}; | ||
|
||
type Entity = { | ||
Id: string; | ||
Type: string; | ||
TypeString: string; | ||
}; | ||
|
||
type EntityLineage = { | ||
MasterPlayerAccountId: string; | ||
NamespaceId: string; | ||
TitleId: string; | ||
TitlePlayerAccountId: string; | ||
VersionNumber: number; | ||
}; | ||
/* | ||
/* | ||
Helper Functions | ||
*/ | ||
const getRoutePrefix = () => { | ||
// Since host.json can omit properties it doesn't want to override, we might | ||
// not have all the properties, so we'll cast the json as `any` to avoid compiler | ||
// errors for sparsely populated host.json files | ||
const castHostJson: any = hostDotJson; | ||
const routePrefix: string | undefined = | ||
castHostJson.extensions?.http?.routePrefix; | ||
return routePrefix || "api"; | ||
}; | ||
|
||
const compressResponseBody = async ( | ||
responseObject: object, | ||
req: HttpRequest | ||
) => { | ||
const encodingsString = (req.headers["accept-encoding"] || "").toLowerCase(); | ||
const responseBytes = Buffer.from(JSON.stringify(responseObject), "utf-8"); | ||
const encodings: string[] = encodingsString | ||
?.replace(/\s/g, "") // remove whitespace | ||
.split(",") | ||
.filter((str) => { | ||
// remove empty string character from array because ''.split results in [''] | ||
return /\S/.test(str); | ||
}); | ||
|
||
// If client doesn't specify accepted encodings, assume identity and respond decompressed | ||
if (!encodings.length || encodings.includes("identity")) { | ||
return responseBytes; | ||
} | ||
|
||
if (encodings.length && !encodings.includes("gzip")) { | ||
throw new Error( | ||
`Unknown compression requested for response. The "Accept-Encoding" haeder values was: ${encodingsString}. Only "Identity" and "GZip" are supported right now.` | ||
); | ||
} | ||
|
||
// gzip returns a Buffer, which is a subclass of Uint8Array | ||
const gzpippedResponse = await gzip(responseBytes); | ||
return gzpippedResponse; | ||
}; | ||
|
||
const getEntityProfile = async ( | ||
callerEntityToken: string, | ||
entity: Entity | undefined | ||
) => { | ||
try { | ||
const profileResponse = await axios.post<EntityProfileResponse>( | ||
"/Profile/GetProfile", | ||
{ | ||
Entity: entity, | ||
}, | ||
{ | ||
baseURL: `https://${process.env.PLAYFAB_TITLE_ID}.playfabapi.com`, | ||
headers: { | ||
"Content-Type": "application/json", | ||
"X-EntityToken": callerEntityToken, | ||
}, | ||
} | ||
); | ||
|
||
return profileResponse; | ||
} catch (error) { | ||
return Promise.reject(error); | ||
} | ||
}; | ||
|
||
/* | ||
Local implementation of ExecuteFunction | ||
*/ | ||
const httpTrigger: AzureFunction = async ( | ||
context: Context, | ||
req: HttpRequest | ||
): Promise<void> => { | ||
const titleId = process.env.PLAYFAB_TITLE_ID!; | ||
if (typeof titleId !== "string") { | ||
throw new Error("Please set your TitleId in local.settings.json!"); | ||
} | ||
|
||
// Extract the caller's entity tocken | ||
const callerEntityToken = req.headers["x-entitytoken"]; | ||
|
||
const entityKey: Entity | undefined = | ||
req.body && req.body?.Entity | ||
? { | ||
Id: req.body?.Entity?.Id, | ||
Type: req.body?.Entity?.Type, | ||
TypeString: req.body?.Entity?.Type, | ||
} | ||
: undefined; | ||
|
||
// Fetch the Profile From PlayFab | ||
const callerEntityProfileResponse = await getEntityProfile( | ||
callerEntityToken, | ||
entityKey | ||
); | ||
|
||
if (callerEntityProfileResponse.data.code !== 200) { | ||
context.res = { | ||
status: callerEntityProfileResponse.data.code, | ||
body: {}, | ||
}; | ||
return Promise.reject(); | ||
} | ||
|
||
const callerEntityProfile = callerEntityProfileResponse.data.data.Profile; | ||
const functionContextInternal = new FunctionContextInternal( | ||
{ Id: titleId, EntityToken: callerEntityToken }, | ||
callerEntityProfile, | ||
req.body.FunctionParameter | ||
); | ||
|
||
const routePrefix = getRoutePrefix(); | ||
|
||
const stopwatch = new StopWatch("stopwatch"); | ||
stopwatch.start("AzureFunction"); | ||
const response = await axios.post( | ||
`/${routePrefix}/${req.body.FunctionName}`, | ||
JSON.stringify(functionContextInternal), | ||
{ | ||
baseURL: "http://localhost:7071", | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
} | ||
); | ||
stopwatch.stop(); | ||
|
||
context.res = { | ||
status: response.status, | ||
body: await compressResponseBody( | ||
{ | ||
code: response.status, | ||
status: response.statusText, | ||
data: { | ||
FunctionName: req.body.FunctionName, | ||
FunctionResult: response.data, | ||
ExecutionTimeMilliseconds: stopwatch.getTask("AzureFunction") | ||
?.timeMills, | ||
FunctionResultTooLarge: false, | ||
}, | ||
}, | ||
req | ||
), | ||
}; | ||
}; | ||
|
||
export default httpTrigger; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# Debugging your PlayFab ExecuteFunction calls locally | ||
|
||
To debug your functions locally | ||
|
||
- Install this package with `npm i playfab_execute_function` | ||
- Create a folder at the root of your project called ExecuteFunction | ||
- Add a file to your new folder called `settings.json` and add the following | ||
|
||
```json | ||
{ | ||
"bindings": [ | ||
{ | ||
"authLevel": "function", | ||
"type": "httpTrigger", | ||
"route": "CloudScript/ExecuteFunction", | ||
"direction": "in", | ||
"name": "req", | ||
"methods": ["get", "post"] | ||
}, | ||
{ | ||
"type": "http", | ||
"direction": "out", | ||
"name": "res" | ||
} | ||
], | ||
"scriptFile": "../dist/ExecuteFunction/index.js" | ||
} | ||
``` | ||
|
||
- Add a file to your ExecuteFunction folder called `index.ts` with the following code | ||
|
||
```typescript | ||
import { AzureFunction, Context, HttpRequest } from "@azure/functions"; | ||
import ExecuteFunction from "playfab_execute_function"; | ||
|
||
const httpTrigger: AzureFunction = async ( | ||
context: Context, | ||
req: HttpRequest | ||
): Promise<void> => { | ||
ExecuteFunction(context, req); | ||
}; | ||
|
||
export default httpTrigger; | ||
``` | ||
|
||
- Add a playfab.local.settings file as described [here](https://docs.microsoft.com/en-us/gaming/playfab/features/automation/cloudscript-af/local-debugging-for-cloudscript-using-azure-functions#configure-playfab-sdk-to-call-local-executefunction-implementation) | ||
|
||
# Running tests | ||
|
||
Run tests with `npm run test` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{ | ||
"version": "2.0", | ||
"logging": { | ||
"applicationInsights": { | ||
"samplingSettings": { | ||
"isEnabled": true, | ||
"excludedTypes": "Request" | ||
} | ||
} | ||
}, | ||
"extensionBundle": { | ||
"id": "Microsoft.Azure.Functions.ExtensionBundle", | ||
"version": "[1.*, 2.0.0)" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
module.exports = { | ||
roots: ["<rootDir>"], | ||
testMatch: [ | ||
"**/__tests__/**/*.+(ts|tsx|js)", | ||
"**/?(*.)+(spec|test).+(ts|tsx|js)", | ||
], | ||
transform: { | ||
"^.+\\.(ts|tsx)$": "ts-jest", | ||
}, | ||
}; |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
{ | ||
"name": "playfab_execute_function", | ||
"version": "1.0.3", | ||
"main": "dist/ExecuteFunction/index.js", | ||
"scripts": { | ||
"build": "tsc -d", | ||
"build:production": "npm run prestart && npm prune --production", | ||
"watch": "tsc --w", | ||
"prestart": "npm run build && func extensions install", | ||
"start:host": "func start", | ||
"start": "npm-run-all --parallel start:host watch", | ||
"test": "jest --verbose", | ||
"clear_jest": "jest --clearCache" | ||
}, | ||
"description": "", | ||
"devDependencies": { | ||
"@azure/functions": "^1.0.1-beta1", | ||
"npm-run-all": "^4.1.5", | ||
"typescript": "^3.3.3", | ||
"jest": "^26.6.3", | ||
"ts-jest": "^26.2.0", | ||
"ts-node": "^8.1.0" | ||
}, | ||
"dependencies": { | ||
"@types/node": "^14.14.7", | ||
"@types/node-gzip": "^1.1.0", | ||
"axios": "^0.21.0", | ||
"node-gzip": "^1.1.2", | ||
"stopwatch-node": "^1.1.0", | ||
"stub-azure-function-context": "^2.0.0-alpha.4" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
{ | ||
"include": [ | ||
"**/*.ts" | ||
], | ||
"compilerOptions": { | ||
"module": "commonjs", | ||
"target": "es6", | ||
"outDir": "dist", | ||
"rootDir": ".", | ||
"sourceMap": true, | ||
"strict": true, | ||
"typeRoots": [ | ||
"./node_modules/@types" | ||
], | ||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ | ||
"resolveJsonModule": true | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assume if no Entity is provided in the request body, we still want the call to succeed? Just calling this out here because I'm not 100% what circumstances lead to this happening, or what the expected behavior is.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, if no entity is provided in the body, the entity in the entity token is used. Passing an entity in the body allows a title to execute a function as a player, for example. But if the title just wanted to execute a function as itself, it can just pass its entity token as normal and not specify an entity in the request body. Most functions are called by players, but we have some cases where customers are calling using a title entity token (see #9)