How to use AWS CDK to look up existing ApiGateway - javascript

I am using AWS CDK to build my lambda, and I would like to register endpoints from the lambda's CDK stack.
I found I can get an existing ApiGateway construct using fromRestApiId(scope, id, restApiId)
(documentation here)
So currently this works well:
//TODO how to look up by ARN instead of restApiId and rootResourceId??
const lambdaApi = apiGateway.LambdaRestApi
.fromRestApiAttributes(this, generateConstructName("api-gateway"), {
restApiId: <API_GATEWAY_ID>,
rootResourceId: <API_GATEWAY_ROOT_RESOURCE_ID>,
});
const lambdaApiIntegration = new apiGateway.LambdaIntegration(lambdaFunction,{
proxy: true,
allowTestInvoke: true,
})
const root = lambdaApi.root;
root.resourceForPath("/v1/meeting/health")
.addMethod("GET", lambdaApiIntegration);
But I would like to deploy to many AWS accounts, and many regions. I don't want to have to hardcode the API_GATEWAY_ID or API_GATEWAY_ROOT_RESOURCE_ID for each account-region pair.
Is there a more generic way to get the existing ApiGateway construct, (e.g. by name or ARN)?
Thank you in advance.

Lets take a simple Api with one resource
const restApi = new apigw.RestApi(this, "my-api", {
restApiName: `my-api`,
});
const mockIntegration = new apigw.MockIntegration();
const someResource = new apigw.Resource(this, "new-resource", {
parent: restApi.root,
pathPart: "somePath",
defaultIntegration: mockIntegration,
});
someResource.addMethod("GET", mockIntegration);
Lets assume we want use this api and resource in another stack, we first need to export
new cdk.CfnOutput(this, `my-api-export`, {
exportName: `my-api-id`,
value: restApi.restApiId,
});
new cdk.CfnOutput(this, `my-api-somepath-export`, {
exportName: `my-api-somepath-resource-id`,
value: someResource.resourceId,
});
Now we need to import in new stack
const restApi = apigw.RestApi.fromRestApiAttributes(this, "my-api", {
restApiId: cdk.Fn.importValue(`my-api-id`),
rootResourceId: cdk.Fn.importValue(`my-api-somepath-resource-id`),
});
and simply add additional resources and methods.
const mockIntegration = new apigw.MockIntegration();
new apigw.Resource(this, "new-resource", {
parent: restApi.root,
pathPart: "new",
defaultIntegration: mockIntegration,
});

Related

How do i query xata data base using vue 3

` methods: {
async getData() {
const xata = getXataClient();
const page = await xata.db.quiz
.select(["questions", "answer", "options", "selected"])
.getPaginated({
pagination: {
size: 15,
},
});
console.log(page.records);
},
},`
I'm new to Xata data base, and i've created a data base but i can't query xata using vue js
You actually can’t query Xata from vue since it’s a frontend framework (more information on why you shouldn’t do this here -> https://xata.io/blog/securely-querying-your-database-on-xata)
If you want help, I invite you to join xata’s discord channel
Have fun!

How to connect useDApp to Rootstock networks?

I am creating a React.js DApp which will interact with Rootstock (RSK) deployed smart contracts.
Recently I came across a React library called useDApp. This library automates the blockchain connection, smart contract interaction and sending transactions by using React hooks and context providers.
​
For example:
const { activateBrowserWallet, account } = useEthers();
const etherBalance = useEtherBalance(account);
​
However, I don't see Rootstock among the supported networks.
​
I have tried to create a Rootstock configuration as described in the docs:
​
const config = {
readOnlyChainId: 30,
readOnlyUrls: {
31: 'https://public-node.testnet.rsk.co',
30: 'https://public-node.rsk.co',
},
};
​
Unfortunately, adding the above appears to be insufficient,
and I was unable to connect to either RSK Mainnet nor RSK Testnet.
Is it possible to configure useDApp to connect to Rootstock?
Yes connecting useDApp to Rootstock is possible.
(1)
Create config objects for both networks
(Rootstock Testnet, Rootstock Mainnet).
(2)
Specify Multicall smart contract addresses, within these config objects.
They should look like this:
const rootstockTestnetExplorerUrl = 'https://explorer.testnet.rsk.co/';
export const RootstockTestnet = {
chainId: 31,
chainName: 'Rootstock Testnet',
isTestChain: true,
isLocalChain: false,
rpcUrl: 'https://public-node.testnet.rsk.co',
// deployed at https://explorer.testnet.rsk.co/address/0xca11bde05977b3631167028862be2a173976ca11
multicallAddress: '0xcA11bde05977b3631167028862bE2a173976CA11',
nativeCurrency: {
name: 'Test Rootstock Bitcoin',
symbol: 'tRBTC',
decimals: 18,
},
getExplorerAddressLink: getAddressLink(rootstockTestnetExplorerUrl),
getExplorerTransactionLink: getTransactionLink(rootstockTestnetExplorerUrl),
};
const rootstockMainnetExplorerUrl = 'https://explorer.rsk.co/';
export const RootstockMainnet = {
chainId: 30,
chainName: 'Rootstock Mainnet',
isTestChain: false,
isLocalChain: false,
rpcUrl: 'https://public-node.rsk.co',
// deployed at https://explorer.rsk.co/address/0xca11bde05977b3631167028862be2a173976ca11
multicallAddress: '0xcA11bde05977b3631167028862bE2a173976CA11',
nativeCurrency: {
name: 'Rootstock Bitcoin',
symbol: 'RBTC',
decimals: 18,
},
getExplorerAddressLink: getAddressLink(rootstockMainnetExplorerUrl),
getExplorerTransactionLink: getTransactionLink(rootstockMainnetExplorerUrl),
};
(3)
Create useDApp configuration using these network configs:
const useDAppConfig = {
networks: [RootstockTestnet, RootstockMainnet],
readOnlyChainId: RootstockMainnet.chainId,
readOnlyUrls: {
[RootstockTestnet.chainId]: RootstockTestnet.rpcUrl,
[RootstockMainnet.chainId]: RootstockMainnet.rpcUrl,
},
};
(4)
Connect the useDApp configuration to DAppProvider (e.g. in index.js)
import { DAppProvider } from '#usedapp/core';
...
root.render(
<DAppProvider config={useDAppConfig}>
<App />
</DAppProvider>,
);
(5)
Now you are ready to go with the blockchain data in your React components:
import {
useEthers,
useEtherBalance,
useTokenBalance,
useSendTransaction,
} from '#usedapp/core';
function App() {
const { activateBrowserWallet, account } = useEthers();
const etherBalance = useEtherBalance(account);
const tokenBalance = useTokenBalance(
tokenAddress,
account,
);
const { sendTransaction } = useSendTransaction();
...
}
bguiz's answer is perfect for the question that you asked but if you are not locked into using useDApp, can I suggest an alternative that maybe a bit easier to implement?
We built rLogin for the use case of connecting the user's wallet to a developer's dapp. There are a bunch of additional integrations like walletConnect, hardware wallets, etc.
For RSK Testnet and RSK Mainnet we have the RPC URLs already in it so you don't have to configure them. rLogin also supports any EVM network so you can use it on Ethereum, Binance, etc.
Here is how you would set it up:
yarn add #rsksmart/rlogin
then in a basic React app, it might look like this:
import RLogin from '#rsksmart/rlogin'
const rLogin = new RLogin({
supportedChains: [30, 31]
})
function App() {
const [provider, setProvider] = useState(null)
const connect = () => {
console.log('connecting...')
rLogin.connect().then(response => {
setProvider(response.provider)
})
}
return (
<div className="App">
<h1>rLogin demo...</h1>
<button onClick={connect}>Connect!</button>
</div>
);
}
The initial rLogin variable needs to be outside the component so it only gets rendered/created once. There are a bunch of additional parameters you can send to the rLogin constructor as well mentioned in the readme. There are also sample applications to see the implementation.

How to properly use context in tRPC?

Let's say I have a very basic API with two sets of endpoints. One set queries and mutates properties about a User, which requires a username parameter, and one set queries and mutates properties about a Post, which requires a post ID. (Let's ignore authentication for simplicity.) I don't currently see a good way to implement this in a DRY way.
What makes the most sense to me is to have a separate Context for each set of routes, like this:
// post.ts
export async function createContext(
opts?: trpcExpress.CreateExpressContextOptions
) {
// pass through post id, throw if not present
}
type Context = trpc.inferAsyncReturnType<typeof createContext>;
const router = trpc
.router()
.query("get", {
resolve(req) {
// get post from database
return post;
},
});
// similar thing in user.ts
// server.ts
const trpcRouter = trpc
.router()
.merge("post.", postRouter)
.merge("user.", userRouter);
app.use(
"/trpc",
trpcExpress.createExpressMiddleware({
router: trpcRouter,
createContext,
})
);
This complains about context, and I can't find anything in the tRPC docs about passing a separate context to each router when merging. Middleware doesn't seem to solve the problem either - while I can fetch the post/user in a middleware and pass it on, I don't see any way to require a certain type of input in a middleware. I would have to throw { input: z.string() } or { input: z.number() } on every query/mutation, which of course isn't ideal.
The docs and examples seem pretty lacking for this (presumably common) use case, so what's the best way forward here?
This functionality has been added in (unreleased as of writing) v10. https://trpc.io/docs/v10/procedures#multiple-input-parsers
const roomProcedure = t.procedure.input(
z.object({
roomId: z.string(),
}),
);
const appRouter = t.router({
sendMessage: roomProcedure
.input(
z.object({
text: z.string(),
}),
)
.mutation(({ input }) => {
// input: { roomId: string; text: string }
}),
});

How can I get the online users list using converse Strophe environment in react js

Is there any method to get the online user list using converse js? I found it is possible by Strophe.js which is already implemented on converse.js.
I created a converse plugin but don't know how can I show the online users.
export const moderationActions = () => {
window.converse.plugins.add('moderation-actions', {
dependencies: [],
initialize: function () {
const _converse = this._converse;
const Strophe = window.converse.env.Strophe;
console.log(Strophe, 'Strophe');
},
});
};
You can try the following:
await api.waitUntil('rosterContactsFetched');
const online_contacts = _converse.roster.models.filter(m => m.presence.get('show') === "online");

Google datastore entity creation and update

I am attempting to update an entity in my datastore kind using sample code from here https://cloud.google.com/datastore/docs/reference/libraries. The actual code is something like this:
/ Imports the Google Cloud client library
const Datastore = require('#google-cloud/datastore');
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
});
// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);
// Prepares the new entity
const task = {
key: taskKey,
data: {
description: 'Buy milk',
},
};
// Saves the entity
datastore
.save(task)
.then(() => {
console.log(`Saved ${task.key.name}: ${task.data.description}`);
})
.catch(err => {
console.error('ERROR:', err);
});
I tried to create a new entity using this code. But when I ran this code and checked the datastore console, there were no entitites created.Also, I am unable to update an existing entity. What could be the reason for this?
I am writing the code in Google Cloud Functions.This is the log when I run this function:
{
insertId: "-ft02akcfpq"
logName: "projects/test-66600/logs/cloudaudit.googleapis.com%2Factivity"
operation: {…}
protoPayload: {…}
receiveTimestamp: "2018-06-15T09:36:13.760751077Z"
resource: {…}
severity: "NOTICE"
timestamp: "2018-06-15T09:36:13.436Z"
}
{
insertId: "000000-ab6c5ad2-3371-429a-bea2-87f8f7e36bcf"
labels: {…}
logName: "projects/test-66600/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2018-06-15T09:36:17.865654673Z"
resource: {…}
severity: "ERROR"
textPayload: "Warning, estimating Firebase Config based on GCLOUD_PROJECT. Intializing firebase-admin may fail"
timestamp: "2018-06-15T09:36:09.434Z"
}
I have tried the same code and it works for me. However, I have noticed that there was a delay before the entities appeared in Datastore. In order to update and overwrite existing entities, use .upsert(task) instead of .save(task) (link to GCP documentation). You can also use .insert(task) instead of .save(task) to store new entities.
Also check that the project id is correct and that you are inspecting the entities for the right kind.

Categories