I have below code to access secret manager
export interface ConfigData {
dbname:string;
dbuser:string;
}
I hvae json data in secret manager like
{
"dbname" : "dbname",
"dbuser" : "dbuser"
}
function
private static async fetchSecretData(){
let config_key = 'projects/xx/xx/xx/versions/latest';
const client = new SecretManagerServiceClient();
const [version] = await client.accessSecretVersion({name:config_key})
console.log(version.payload?.data )
return version.payload?.data?.toString() as unknown as ConfigData;
}
But I need to cast this as unknown as ConfigData,
I want to cast this ConfigData without making it unknown.
If there is no alternate to do this, then what is the best option to get the keys from this unknown object.
Thanks
Two remarks:
toString() will return a string representation of whatever data is, so casting this to any other type is not going work.SecretManagerServiceClient is a part of the Google Cloud Secret Manager API. You don't have to provide your own types for those as the @google-cloud/secret-manager package already comes with its own type definitions. /** Properties of a SecretPayload. */
interface ISecretPayload {
/** SecretPayload data */
data?: (Uint8Array|string|null);
}
To me it's not quite clear what this data is supposed to be. If it's a JSON string then you need to parse it with JSON.parse(version.payload.data) and then append as ConfigData to that, to let TypeScript know the shape of the output. If it's a Uint8Array you need to .toString it first before parsing it with JSON.parse.
So you would get something like:
private static async fetchSecretData() {
let config_key = 'projects/xx/xx/xx/versions/latest';
const client = new SecretManagerServiceClient();
const [version] = await client.accessSecretVersion({name:config_key})
if(version?.payload?.data) {
return JSON.parse(version.payload.data) as ConfigData
} else {
return null;
}
}