NestJs ParseEnumPipe can't be resolve - javascript

I am using the NestJs framework (love it by the way) and I want to check the incoming data so it conforms with an Enum in Typscript. So I have the following:
enum ProductAction {
PURCHASE = 'PURCHASE',
}
#Patch('products/:uuid')
async patchProducts(
#Param('uuid', ParseUUIDPipe) uuid: string,
#Body('action', ParseEnumPipe) action: ProductAction,
) {
switch(action) {
... code
}
The weird thing is that when I run this code, the first pipe gets compiled
2022-07-21 16:53:51 [error] [ExceptionHandler] Nest can't resolve dependencies of the ParseEnumPipe (?, Object). Please make sure that the argument Object at index [0] is available in the FriendsModule context.
What I am doing wrong?

You should use #Body('action', new ParseEnumPipe(ProductAction)) action: ProductAction because enums aren't directly reflected for Nest to read the metadata of, and because Nest is otherwise trying to figure out how to inject Object when it really should be injecting the enum.

Related

add dependency on custom resource cdk

I have the following problem that i cannot add dependsOn on a cfnResource for a CustomResource
const cfnRawTable = new timestream.CfnTable(this, 'MyCfnTableRaw', {
databaseName: dbName,
// the properties below are optional
magneticStoreWriteProperties: {
enableMagneticStoreWrites: true,
},
retentionProperties: {
magneticStoreRetentionPeriodInDays: '1825',
memoryStoreRetentionPeriodInHours: '8640',
},
tableName: rawtable,
})
let insertionLambda = new cdk.CustomResource(this, 'insertionlambda', {
serviceToken:
'arn:aws:lambda:' +
cdk.Fn.ref('region') +
'738234497474:function:timestreaminsertion-' +
cdk.Fn.ref('env'),
})
cfnRawTable.addDependsOn(insertionLambda)
I get the error Argument of type 'CustomResource' is not assignable to parameter of type 'CfnResource'
I think you have todo it the other way around:
insertionLambda.addDependsOn(cfnRawTable);
 Use CDK's Construct dependencies instead:
cfnRawTable.node.addDependency(insertionLambda);
addDependsOn is a low-level CloudFormation feature that is only available in L1 CloudFormation resources. The high-level .node.addDependency is available with all Constructs.
In this case, though, it does seem from the naming that your insertion lambda depends on the table, not the other way around, like #Martin Muller pointed out. You can still use the above, just swap them around. This guess an totally be incorrect, of course, maybe your lambda is not inserting into this particular table.
If you make any reference to the resource from another, it will automatically add the dependency.
As an example, adding the cfnRawTable.attrArn to the properties argument for CustomResource will cause the dependency relationship to be created.
cdk.CustomResource(
...,
{
properties: {'tablearn': cfnRawTable.attrArn}
},
)
Alternatively, you can declare a dependency without needing to make any reference using .node.addDependency
insertionLambda.node.addDependency(CfnRawTable)

How to cast a plain json object to typeorm entity

There is a transformer class called PlainObjectToNewEntityTransformer, if I need to invoke its transform function, I have to pass in the EntityMetadata which requires connection, I think casting doesn’t really need connection. The current workaround is to do the following by just assign in constructor, but this won’t preserve the schema since the field keys are often changed.
#Entity('myentities')
export class MyEntity {
constructor(partial?: Partial<MyEntity>) {
if (partial) {
Object.assign(this, partial);
}
}
}
const entity = new MyEntity(json);
I am not sure if the casting can be done in a proper way.
I am currently attempting to work with PlainObjectToNewEntityTransformer().
I was able to use getConnection() to retrieve the EntityMetadata[]. I see that getConnection.hasMetadata(*entity name*) and getConnection.getMetadata(*entity name*) are available. If I understood your question correctly, I believe one of these will provide the EntityMetadata you are seeking.

Typescript using the incorrect type with jest when there are multiple available

I am new to typescript and noticed a behaviour I wasn't expecting. When I go to mock a named import with the js-cookie package, it mocks a particular instance of the property, but incorrectly chooses the correct type to use.
import Cookies from "js-cookie"
import { mocked } from "ts-jest/utils"
jest.mock("js-cookie")
const mockedCookies = mocked(Cookies, true)
beforeEach(() => {
mockedCookies.get = jest.fn().mockImplementation(() => "123")
})
it("SampleTest", () => {
//this line throws an error as it is using a difference interface to check against
mockedCookies.get.mockImplementationOnce(() => undefined)
//continue test...
}
In the #types/js-cookies there are two definitions for this and it always uses the get() version when I reference it as mockCookie.get.<some-jest-function>. Hence, I get typescript errors saying Type 'undefined' is not assignable to type '{ [key: string]: string; }'..
/**
* Read cookie
*/
get(name: string): string | undefined;
/**
* Read all available cookies
*/
get(): {[key: string]: string};
I can fix this by always redeclaring the jest.fn() every time, but would prefer to use the handy jest functions (like mockImplementationOnce).
Am I doing something wrong? Is there a way to enforce which get type to use?
I am not sure if this helps but you may use mockedCookies.get.mockImplementationOnce(() => ({})) as of now to get rid of this error.
Updated:
After some testing, I see that these mock functions are stored in dictionary style format. The last function with same name always replace the previous ones.
If you try to move get(name: string) below get() from 'js-cookie', you will see that this error is gone.
So there is no way to get specific function with same name.
I don't know much about your use-case, but you may do better not using jest mocks and instead use jest's jsdom environment. You can then set up your environment using js-cookie's methods.
In your example, you can run Cookies.remove(<cookie name>); as setup, then when you run Cookies.get(<cookie name>), you should get undefined, no? You do have to be careful about state persisting between tests, but you have to do that in the mock version of this anyway.
I tested jsdom's implementation for a couple simple cases, but I have no idea how thorough their mock is for more advanced use cases involving multiple domains, etc.

How set graphql-js module in debug mode

i'm new in graphql and setting up server graphql api use [https://github.com/graphql/graphql-js] graphql-js.
I followed their document and everything work, expect 1 problem:
when make query and got error from deep module, graphql-js try catch error and return result with errors: [...] property, but in terminal console say nothing. I would like force grahql-js return actual Error object so i can debug issue when looking to stack.
this is code in api
query: (ctx) -> (
await graphql(
schema
query
context
graphContext
variables
)
)
I search a lot of topic but no ones say about set this package in debug mode, also no see any parameter allow set debug. Anyone know about this?
Thanks !
Normally, you would use a library like express-graphql or apollo-server (or apollo-server-express, apollo-server-hapi, etc.) to provide an endpoint for your GraphQL API. Unless your use case prohibits you from doing so, I would strongly encourage you to utilize one of these libraries since they provide a number of additional features that are helpful in both development and production.
You can add logging to your endpoint when using one of these libraries simply by providing a custom formatError function in your configuration. See each library's documentation here and here. As a bonus, if you use Apollo, then the full stack trace will be exposed inside of your errors array anyway, but only in development.
If you're calling the graphql function directly in your code somewhere, then you can just log the errors yourself. The call to graphql returns a Promise that resolves to a ExecutionResult object, which includes both your data and errors. So you can do something like:
const result = await graphql(/* your args */)
if (result.errors) {
result.errors.forEach((error) => {
// log the error
})
}
You have to instantiate the graph object with the debug option enabled, like this
var graph = graphql("/api", { debug: true })

Return vue instance from vue.js filter (Vue.js 2)

I'm using filter function for internationalization like this:
<div>{{ "hello" | message }}<div>
message is a filter function that depends on global Vue.config.lang variable.
It works great, but if I change Vue.config.lang, message doesn't rerender.
I wanted to make message rerender anytime Vue.config.lang changes, so I changed my filter function from
message => locale_messages[Vue.config.lang][message]
to
message => new Vue({
template: '{{ message }}',
computed: {
message() { return locale_messages[Vue.config.lang][message]; }
}
})
But it doesn't work. Getting this error:
Uncaught TypeError: Converting circular structure to JSON
at Object.stringify (<anonymous>)
....
Is there anything I can do to make it work? I'm new to Vue.js and can't find a working solution.
Like Evan says, Filters should be pure, so thay can't use a global variable as key to get values from externals arrays. Because of side effects.
So, there is three solutions at your problem that comes in my mind :
Replace filters by methods.
Use vue-i18-n, a simple and powerful module for translation
Use a store system (vuex) wich provides you getters, and helps you manage a global state.
Personnaly I love to use vuex and vue-i18-n together.
In that way I can centralize my data and the language in use. I can also serve specific data in several languages using the store, and let vue-i18-n cares about all the strings in the project.
New to Vue myself, so not quite sure how global variables work, but you can definitely pass params to a custom filter - even a Vue reference. You can do this:
<!-- this = a reference to the vue instance -->
<span class="display-3">{{value|FormatValue(this)}}</span>
[...]
props: ["aIsPercentNeeded"],
[...]
Vue.filter("FormatValue", function (aValue, aVueInstance)
{
if (!aVueInstance["aIsPercentNeeded"])
{
return aValue;
}
return aValue + "%";
});

Categories