Skip to content

Commit

Permalink
feat(node-proto): add example with fromBinary() (#509)
Browse files Browse the repository at this point in the history
add example with fromBinary()
  • Loading branch information
bobaaaaa authored Jun 26, 2023
1 parent b34fa73 commit 6df8233
Showing 1 changed file with 37 additions and 12 deletions.
49 changes: 37 additions & 12 deletions node-proto/examples/protobuf-es/client.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { performance } from 'node:perf_hooks';
import fetch from 'node-fetch';
import { GetNavigationResponse } from '../../stroeer/navigation/v1/navigation_service_pb';

Expand All @@ -15,29 +16,53 @@ const getAPIEndpoint = () => {
return validateEnvVar(apiEndpoint, 'API_ENDPOINT');
};

function fetchData() {
function fetchData(acceptHeader: 'json' | 'protobuf' = 'json') {
return fetch(getAPIEndpoint(), {
headers: {
'user-agent': 'tapir_node_buf_demo',
Accept: `application/${acceptHeader}`,
},
}).then((response) => {
if (!response.ok) {
throw new Error(
`The response is not ok. Status: ${response.status}. Text: ${response.statusText}`
);
}
return response.json();
return response;
});
}

fetchData()
.then((data) => {
console.log('success');
const navigationResponse = GetNavigationResponse.fromJson(data);
console.log({
navi: JSON.stringify(navigationResponse.navigationMenu, null, 2),
const fetchJSON = () => {
const start = performance.now();
fetchData()
.then((response) => response.json())
.then((data) => {
console.log('success: json');
GetNavigationResponse.fromJson(data);
const end = performance.now();

console.log('json time', end - start);
})
.catch((error) => {
console.error('There was an error while fetching the data', error);
});
})
.catch((error) => {
console.error('There was an error while fetching the data', error);
});
};

const fetchBinary = () => {
const start = performance.now();
fetchData('protobuf')
.then((response) => response.buffer())
.then((data) => {
console.log('success: binary');
GetNavigationResponse.fromBinary(data);
const end = performance.now();

console.log('binary time', end - start);
})
.catch((error) => {
console.error('There was an error while fetching the data', error);
});
};

fetchJSON();
fetchBinary();

0 comments on commit 6df8233

Please sign in to comment.