Skip to content
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
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions typescript/.funcignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.js.map
*.ts
.git*
.vscode
local.settings.json
test
43 changes: 43 additions & 0 deletions typescript/.gitignore
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
5 changes: 5 additions & 0 deletions typescript/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"ms-azuretools.vscode-azurefunctions"
]
}
30 changes: 30 additions & 0 deletions typescript/.vscode/launch.json
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"
}
]
}
11 changes: 11 additions & 0 deletions typescript/.vscode/settings.json
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
}
}
31 changes: 31 additions & 0 deletions typescript/.vscode/tasks.json
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": []
}
]
}
18 changes: 18 additions & 0 deletions typescript/ExecuteFunction/function.json
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"
}
231 changes: 231 additions & 0 deletions typescript/ExecuteFunction/index.test.ts
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 () => {
Copy link
Author

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.

Copy link
Contributor

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)

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();
});
});
Loading