Skip to content

Commit

Permalink
fix: correct order of in which response status and headers are written (
Browse files Browse the repository at this point in the history
#381)

* fix: add missing const declaration

* chore: cleanup some unused vars and add types

* fix: correct order of in which response status and headers are written

* test: use of http_headers and success_code metadata together
  • Loading branch information
matteo-cristino authored Oct 24, 2024
1 parent dec0216 commit 80e6f18
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 20 deletions.
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,8 @@ Dir.ready(async () => {
const endpoint = Dir.endpoint(path);
if (!endpoint) return;
const pathArray = path.split('.');
ext = pathArray.pop() as string;
secondExt = pathArray.pop() as string;
const ext = pathArray.pop() as string;
const secondExt = pathArray.pop() as string;
let event: Events;
if (
FILE_EXTENSIONS.contract.includes(ext) ||
Expand All @@ -259,8 +259,8 @@ Dir.ready(async () => {

Dir.onDelete(async (path: string) => {
const pathArray = path.split('.');
ext = pathArray.pop() as string;
secondExt = pathArray.pop() as string;
const ext = pathArray.pop() as string;
const secondExt = pathArray.pop() as string;
let endpoint: Endpoints | undefined;
let event: Events;
if (
Expand Down
32 changes: 16 additions & 16 deletions src/routeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import fs from 'fs';
import _ from 'lodash';
import { IMeta, Logger, type ILogObj } from 'tslog';
import { App, HttpResponse, TemplatedApp } from 'uWebSockets.js';
import { App, HttpRequest, HttpResponse, TemplatedApp } from 'uWebSockets.js';
import { execute as slangroomChainExecute } from '@dyne/slangroom-chain';

import { reportZenroomError } from './error.js';
Expand Down Expand Up @@ -111,7 +111,7 @@ export const runPrecondition = async (preconditionPath: string, data: Record<str
await s.execute(zen, { data, keys });
};

const parseDataFunctions = {
const parseDataFunctions: Record<string, (data: string) => Record<string, unknown>> = {
'application/json': (data: string) => JSON.parse(data),
'application/x-www-form-urlencoded': (data: string) => {
const res: Record<string, unknown> = {};
Expand All @@ -128,10 +128,8 @@ const parseDataFunctions = {
const checkAndGetHeaders = (
res: HttpResponse,
req: HttpRequest,
LOG: Logger<ILogObj>,
action: Events,
path: string,
metadata: JSONSchema,
notAllowed: boolean
): Headers | undefined => {
if (action === 'delete') {
Expand All @@ -144,8 +142,8 @@ const checkAndGetHeaders = (
}
const headers: Headers = {};
headers.request = {};
req.forEach((k, v) => {
headers.request[k] = v;
req.forEach((k: string, v: string) => {
headers.request![k] = v;
});
return headers;
};
Expand Down Expand Up @@ -199,8 +197,8 @@ const execZencodeAndReply = async (
if ('chain' in endpoint) {
const dataFormatted = data ? JSON.stringify(data) : undefined;
const parsedChain = eval(endpoint.chain)();
const res = await slangroomChainExecute(parsedChain, dataFormatted);
jsonResult = JSON.parse(res);
const slangRes = await slangroomChainExecute(parsedChain, dataFormatted);
jsonResult = JSON.parse(slangRes);
} else {
const s = SlangroomManager.getInstance();
({ result: jsonResult } = await s.execute(endpoint.contract, { keys, data, conf }));
Expand All @@ -225,16 +223,17 @@ const execZencodeAndReply = async (
}
const slangroomResult = JSON.stringify(jsonResult);
res.cork(() => {
res
.writeStatus(metadata.successCode)
.writeHeader('Content-Type', metadata.successContentType)
.writeHeader('Access-Control-Allow-Origin', '*')

if (metadata.httpHeaders && headers.response !== undefined) {
for (const [k, v] of Object.entries(headers.response)) {
res.writeHeader(k, v);
}
}
res
.writeStatus(metadata.successCode)
.writeHeader('Content-Type', metadata.successContentType)
.writeHeader('Access-Control-Allow-Origin', '*')
.end(slangroomResult);
res.end(slangroomResult);
return;
});
} catch (e) {
Expand All @@ -258,7 +257,7 @@ const generatePost = (
) => {
const { path, metadata } = endpoint;
app.post(path, (res, req) => {
const headers = checkAndGetHeaders(res, req, LOG, action, path, metadata, metadata.disablePost);
const headers = checkAndGetHeaders(res, req, action, path, metadata.disablePost);
if (!headers) return;
if (headers.request?.['content-type'] !== metadata.contentType) {
unsupportedMediaType(res, new Error(`Unsupported media type on ${path}`));
Expand All @@ -277,7 +276,8 @@ const generatePost = (
if (isLast) {
let data;
try {
const parseFun = parseDataFunctions[metadata.contentType];
const parseFun: (data: string) => Record<string, unknown> | undefined =
parseDataFunctions[metadata.contentType];
if (!parseFun) {
unsupportedMediaType(res, new Error(`Unsupported media type ${metadata.contentType}`));
}
Expand Down Expand Up @@ -314,7 +314,7 @@ const generateGet = (
) => {
const { path, metadata } = endpoint;
app.get(path, async (res, req) => {
const headers = checkAndGetHeaders(res, req, LOG, action, path, metadata, metadata.disableGet);
const headers = checkAndGetHeaders(res, req, action, path, metadata.disableGet);
if (!headers) return;
/**
* Code may break on `slangroom.execute`
Expand Down
5 changes: 5 additions & 0 deletions tests/fixtures/meta/set_http_headers_response.metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"success_code": "302",
"error_code": "500",
"http_headers": true
}
8 changes: 8 additions & 0 deletions tests/fixtures/meta/set_http_headers_response.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"type:": "object",
"properties": {
"http_headers": {
"type": "object"
}
}
}
9 changes: 9 additions & 0 deletions tests/fixtures/meta/set_http_headers_response.zen
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Given I have a 'string dictionary' named 'http_headers'

When I set 'location' to 'https://example.com/cb?code=aaaa' as 'string'
When I create the 'string dictionary' named 'response'

When I move 'location' in 'response'
When I move 'response' in 'http headers'

Then print the 'http_headers'
9 changes: 9 additions & 0 deletions tests/workflow.stepci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ tests:
http_headers:
response:
Cache-Control: no-store
- name: set http_headers response
http:
url: http://${{env.host}}/meta/set_http_headers_response
method: GET
followRedirects: false
check:
headers:
Location: https://example.com/cb?code=aaaa
status: 302

hello:
steps:
Expand Down

0 comments on commit 80e6f18

Please sign in to comment.