-
Notifications
You must be signed in to change notification settings - Fork 33
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
feat: switch to Azure Functions v4 #177
base: main
Are you sure you want to change the base?
Changes from all commits
c7da645
595addf
db3cba8
3340de3
9337132
53ec98a
4cbffd0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,22 @@ | ||
module.exports = async function (context, req) { | ||
context.log('JavaScript HTTP trigger function processed a request.'); | ||
|
||
const name = req.query.name || (req.body && req.body.name); | ||
const responseMessage = name | ||
? 'Hello, ' + name + '. This HTTP triggered function executed successfully.' | ||
: 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.'; | ||
|
||
context.res = { | ||
// status: 200, /* Defaults to 200 */ | ||
body: responseMessage | ||
}; | ||
}; | ||
const { app } = require('@azure/functions'); | ||
|
||
app.http('httpTrigger1', { | ||
methods: ['GET', 'POST'], | ||
handler: async (req, context) => { | ||
context.log('JavaScript HTTP trigger function processed a request.'); | ||
|
||
let name; | ||
if (req.query.has('name')) { | ||
name = req.query.get('name') | ||
} else { | ||
let body = await req.json(); | ||
name = body.name; | ||
} | ||
|
||
const responseMessage = name | ||
? 'Hello, ' + name + '. This HTTP triggered function executed successfully.' | ||
: 'This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.'; | ||
|
||
return { body: responseMessage }; | ||
} | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,6 @@ | ||
{} | ||
{ | ||
"main": "sk_render/index.js", | ||
"dependencies": { | ||
"@azure/functions": "^4" | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ import { | |
getClientPrincipalFromHeaders, | ||
splitCookiesFromHeaders | ||
} from './headers'; | ||
import { app } from '@azure/functions'; | ||
|
||
// replaced at build time | ||
// @ts-expect-error | ||
|
@@ -17,99 +18,101 @@ const server = new Server(manifest); | |
const initialized = server.init({ env: process.env }); | ||
|
||
/** | ||
* @typedef {import('@azure/functions').AzureFunction} AzureFunction | ||
* @typedef {import('@azure/functions').Context} Context | ||
* @typedef {import('@azure/functions').InvocationContext} InvocationContext | ||
* @typedef {import('@azure/functions').HttpRequest} HttpRequest | ||
* @typedef {import('@azure/functions').HttpResponse} HttpResponse | ||
*/ | ||
|
||
/** | ||
* @param {Context} context | ||
*/ | ||
export async function index(context) { | ||
const request = toRequest(context); | ||
|
||
if (debug) { | ||
context.log( | ||
'Starting request', | ||
context?.req?.method, | ||
context?.req?.headers?.['x-ms-original-url'] | ||
); | ||
context.log(`Original request: ${JSON.stringify(context)}`); | ||
context.log(`Request: ${JSON.stringify(request)}`); | ||
} | ||
|
||
const ipAddress = getClientIPFromHeaders(request.headers); | ||
const clientPrincipal = getClientPrincipalFromHeaders(request.headers); | ||
|
||
await initialized; | ||
const rendered = await server.respond(request, { | ||
getClientAddress() { | ||
return ipAddress; | ||
}, | ||
platform: { | ||
clientPrincipal, | ||
context | ||
app.http('sk_render', { | ||
methods: ['HEAD', 'GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'], | ||
/** | ||
* | ||
* @param {HttpRequest} httpRequest | ||
* @param {InvocationContext} context | ||
*/ | ||
handler: async (httpRequest, context) => { | ||
if (debug) { | ||
context.log( | ||
'Starting request', | ||
httpRequest.method, | ||
httpRequest.headers.get('x-ms-original-url') | ||
); | ||
context.log(`Request: ${JSON.stringify(httpRequest)}`); | ||
} | ||
}); | ||
|
||
const response = await toResponse(rendered); | ||
const request = toRequest(httpRequest); | ||
|
||
const ipAddress = getClientIPFromHeaders(request.headers); | ||
const clientPrincipal = getClientPrincipalFromHeaders(request.headers); | ||
|
||
await initialized; | ||
const rendered = await server.respond(request, { | ||
getClientAddress() { | ||
return ipAddress; | ||
}, | ||
platform: { | ||
user: httpRequest.user, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
clientPrincipal, | ||
context | ||
} | ||
}); | ||
|
||
if (debug) { | ||
context.log(`SK headers: ${JSON.stringify(Object.fromEntries(rendered.headers.entries()))}`); | ||
context.log(`Response: ${JSON.stringify(rendered)}`); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not continue to log the response here? |
||
} | ||
|
||
if (debug) { | ||
context.log(`SK headers: ${JSON.stringify(Object.fromEntries(rendered.headers.entries()))}`); | ||
context.log(`Response: ${JSON.stringify(response)}`); | ||
return toResponse(rendered); | ||
} | ||
|
||
context.res = response; | ||
} | ||
}); | ||
|
||
/** | ||
* @param {Context} context | ||
* @param {HttpRequest} httpRequest | ||
* @returns {Request} | ||
* */ | ||
function toRequest(context) { | ||
const { method, headers, rawBody, body } = context.req; | ||
// because we proxy all requests to the render function, the original URL in the request is /api/__render | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we keep the comment? |
||
// this header contains the URL the user requested | ||
const originalUrl = headers['x-ms-original-url']; | ||
*/ | ||
function toRequest(httpRequest) { | ||
const originalUrl = httpRequest.headers.get('x-ms-original-url'); | ||
|
||
// SWA strips content-type headers from empty POST requests, but SK form actions require the header | ||
// https://github.com/geoffrich/svelte-adapter-azure-swa/issues/178 | ||
if (method === 'POST' && !body && !headers['content-type']) { | ||
headers['content-type'] = 'application/x-www-form-urlencoded'; | ||
if ( | ||
httpRequest.method === 'POST' && | ||
!httpRequest.body && | ||
!httpRequest.headers.get('content-type') | ||
) { | ||
httpRequest.headers.set('content-type', 'application/x-www-form-urlencoded'); | ||
} | ||
|
||
/** @type {RequestInit} */ | ||
const init = { | ||
method, | ||
headers: new Headers(headers) | ||
}; | ||
|
||
if (method !== 'GET' && method !== 'HEAD') { | ||
init.body = Buffer.isBuffer(body) | ||
? body | ||
: typeof rawBody === 'string' | ||
? Buffer.from(rawBody, 'utf-8') | ||
: rawBody; | ||
} | ||
Comment on lines
-87
to
-93
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So this logic isn't needed any more under the v4 model? |
||
/** @type {Record<string, string>} */ | ||
const headers = {}; | ||
httpRequest.headers.forEach((value, key) => { | ||
if (key !== 'x-ms-original-url') { | ||
headers[key] = value; | ||
} | ||
}); | ||
|
||
return new Request(originalUrl, init); | ||
return new Request(originalUrl, { | ||
method: httpRequest.method, | ||
headers: new Headers(headers), | ||
// @ts-ignore | ||
body: httpRequest.body, | ||
duplex: 'half' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why set this property? |
||
}); | ||
} | ||
|
||
/** | ||
* @param {Response} rendered | ||
* @returns {Promise<Record<string, any>>} | ||
* @returns {Promise<HttpResponse>} | ||
*/ | ||
async function toResponse(rendered) { | ||
const { status } = rendered; | ||
const resBody = new Uint8Array(await rendered.arrayBuffer()); | ||
|
||
const { headers, cookies } = splitCookiesFromHeaders(rendered.headers); | ||
|
||
return { | ||
status, | ||
body: resBody, | ||
status: rendered.status, | ||
// @ts-ignore | ||
body: rendered.body, | ||
headers, | ||
cookies, | ||
isRaw: true | ||
enableContentNegotiation: false | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,35 @@ | ||
import * as set_cookie_parser from 'set-cookie-parser'; | ||
|
||
/** | ||
* @typedef {import('@azure/functions').Cookie} Cookie | ||
*/ | ||
|
||
/** | ||
* Splits 'set-cookie' headers into individual cookies | ||
* @param {Headers} headers | ||
* @returns {{ | ||
* headers: Record<string, string>, | ||
* cookies: set_cookie_parser.Cookie[] | ||
* headers: Headers, | ||
* cookies: Cookie[] | ||
* }} | ||
*/ | ||
export function splitCookiesFromHeaders(headers) { | ||
/** @type {Record<string, string>} */ | ||
const resHeaders = {}; | ||
|
||
/** @type {set_cookie_parser.Cookie[]} */ | ||
/** @type {Cookie[]} */ | ||
const resCookies = []; | ||
|
||
headers.forEach((value, key) => { | ||
if (key === 'set-cookie') { | ||
const cookieStrings = set_cookie_parser.splitCookiesString(value); | ||
// @ts-ignore | ||
resCookies.push(...set_cookie_parser.parse(cookieStrings)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like this is due to a type mismatch on the
|
||
} else { | ||
resHeaders[key] = value; | ||
} | ||
}); | ||
|
||
return { headers: resHeaders, cookies: resCookies }; | ||
return { headers: new Headers(resHeaders), cookies: resCookies }; | ||
} | ||
|
||
/** | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,26 +7,7 @@ import esbuild from 'esbuild'; | |
* @typedef {import('esbuild').BuildOptions} BuildOptions | ||
*/ | ||
|
||
const ssrFunctionRoute = '/api/__render'; | ||
|
||
const functionJson = ` | ||
{ | ||
"bindings": [ | ||
{ | ||
"authLevel": "anonymous", | ||
"type": "httpTrigger", | ||
"direction": "in", | ||
"name": "req", | ||
"route": "__render" | ||
}, | ||
{ | ||
"type": "http", | ||
"direction": "out", | ||
"name": "res" | ||
} | ||
] | ||
} | ||
`; | ||
const ssrFunctionRoute = '/api/sk_render'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The docs need to be updated to mention that this route is now reserved https://github.com/derkoe/svelte-adapter-azure-swa/blob/7a855e8885385ba12a8a71f603dc6f5e8537b732/README.md#L122-L123 |
||
|
||
/** | ||
* Validate the static web app configuration does not override the minimum config for the adapter to work correctly. | ||
|
@@ -123,6 +104,11 @@ If you want to suppress this error, set allowReservedSwaRoutes to true in your a | |
})};\n` | ||
); | ||
|
||
// add @azure/functions to esbuildOptions.external if not already set - this is needed by the Azure Functiions v4 runtime | ||
if (!esbuildOptions.external?.includes('@azure/functions')) { | ||
esbuildOptions.external = [...(esbuildOptions.external || []), '@azure/functions']; | ||
} | ||
|
||
/** @type {BuildOptions} */ | ||
const default_options = { | ||
entryPoints: [entry], | ||
|
@@ -137,7 +123,6 @@ If you want to suppress this error, set allowReservedSwaRoutes to true in your a | |
}; | ||
|
||
await esbuild.build(default_options); | ||
writeFileSync(join(functionDir, 'function.json'), functionJson); | ||
|
||
builder.log.minor('Copying assets...'); | ||
builder.writeClient(staticDir); | ||
|
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.
There's a external Azure function in this folder that also needs to be converted to the v4 model