ERROR [ExceptionsHandler] Invalid role NestJs Jest Tests - javascript

I have introduced an nest HTTP exception filter in the project and included it globally in main.ts
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(new HttpExceptionFilter(httpAdapter));
NestJS Jest tests are failing with below error.
[Nest] 13076 - 09/03/2022, 2:16:50 PM ERROR [ExceptionsHandler] Invalid role(s): []
AccessControlError: Invalid role(s): []
at new AccessControlError (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/accesscontrol/lib/core/AccessControlError.js:24:28)
at Object.getFlatRoles (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/accesscontrol/lib/utils.js:550:19)
at Object.getUnionAttrsOfRoles (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/accesscontrol/lib/utils.js:739:27)
at new Permission (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/accesscontrol/lib/core/Permission.js:51:43)
at RolesBuilder.Object.<anonymous>.AccessControl.permission (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/accesscontrol/lib/AccessControl.js:481:16)
at AclFilterResponseInterceptor.intercept (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/src/interceptors/aclFilterResponse.interceptor.ts:25:42)
at /Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/#nestjs/core/interceptors/interceptors-consumer.js:23:36
at InterceptorsConsumer.intercept (/Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/#nestjs/core/interceptors/interceptors-consumer.js:25:24)
at /Users/shubhamjain/SJ/Projects/amplication/packages/amplication-data-service-generator/generated/server/node_modules/#nestjs/core/router/router-execution-context.js:46:60
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Edit1
Every Controller's endpoint has something related to using roles.
#common.UseInterceptors(AclValidateRequestInterceptor)
#nestAccessControl.UseRoles({
resource: "Customer",
action: "create",
possession: "any",
})
#common.Post()
#swagger.ApiCreatedResponse({ type: Customer })
#swagger.ApiForbiddenResponse({ type: errors.ForbiddenException })
async create(#common.Body() data: CustomerCreateInput): Promise<Customer> {
Any pointers to debug this problem would be appreciated.

Related

I'm using "sails": "~1.2.4". I'm trying to connect to a MongoDb. But When I try to sails lift I get this error:

**Error Type**
error: A hook (`orm`) failed to load!
error: Could not tear down the ORM hook. Error details: Error: Consistency violation: Attempting to tear down a datastore (`default`) which is not currently registered with this adapter. This is usually due to a race condition in userland code (e.g. attempting to tear down the same ORM instance more than once), or it could be due to a bug in this adapter. (If you get stumped, reach out at http://sailsjs.com/support.)
at Object.teardown (D:\HTML\Sails\test\node_modules\sails-mongo\lib\index.js:390:19)
at D:\HTML\Sails\test\node_modules\waterline\lib\waterline.js:758:27
at D:\HTML\Sails\test\node_modules\waterline\node_modules\async\dist\async.js:3047:20
at eachOfArrayLike (D:\HTML\Sails\test\node_modules\waterline\node_modules\async\dist\async.js:1002:13)
at eachOf (D:\HTML\Sails\test\node_modules\waterline\node_modules\async\dist\async.js:1052:9)
at Object.eachLimit (D:\HTML\Sails\test\node_modules\waterline\node_modules\async\dist\async.js:3111:7)
at Object.teardown (D:\HTML\Sails\test\node_modules\waterline\lib\waterline.js:742:11)
at Hook.teardown (D:\HTML\Sails\test\node_modules\sails-hook-orm\index.js:246:30)
at Sails.wrapper (D:\HTML\Sails\test\node_modules\#sailshq\lodash\lib\index.js:3282:19)
at Object.onceWrapper (events.js:421:28)
at Sails.emit (events.js:315:20)
at Sails.EventEmitter.emit (domain.js:482:12)
at Sails.emitter.emit (D:\HTML\Sails\test\node_modules\sails\lib\app\private\after.js:56:26)
at D:\HTML\Sails\test\node_modules\sails\lib\app\lower.js:67:11
at beforeShutdown (D:\HTML\Sails\test\node_modules\sails\lib\app\lower.js:45:12)
at Sails.lower (D:\HTML\Sails\test\node_modules\sails\lib\app\lower.js:49:3)
at Sails.wrapper [as lower] (D:\HTML\Sails\test\node_modules\#sailshq\lodash\lib\index.js:3282:19)
at whenSailsIsReady (D:\HTML\Sails\test\node_modules\sails\lib\app\lift.js:68:13)
at D:\HTML\Sails\test\node_modules\async\dist\async.js:3861:9
at D:\HTML\Sails\test\node_modules\async\dist\async.js:421:16
at iterateeCallback (D:\HTML\Sails\test\node_modules\async\dist\async.js:924:17)
at D:\HTML\Sails\test\node_modules\async\dist\async.js:906:16
error:
error: Error: Consistency violation: Unexpected error creating db connection manager:
```
MongoError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
name: 'MongoError'
}]
at flaverr (D:\HTML\Sails\test\node_modules\flaverr\index.js:94:15)
at Function.module.exports.parseError (D:\HTML\Sails\test\node_modules\flaverr\index.js:371:12)
at Function.handlerCbs.error (D:\HTML\Sails\test\node_modules\machine\lib\private\help-build-machine.js:665:56)
at connectCb (D:\HTML\Sails\test\node_modules\sails-mongo\lib\private\machines\create-manager.js:130:22)
at connectCallback (D:\HTML\Sails\test\node_modules\mongodb\lib\mongo_client.js:428:5)
at D:\HTML\Sails\test\node_modules\mongodb\lib\mongo_client.js:335:11
at processTicksAndRejections (internal/process/task_queues.js:79:11)
```
at Object.error (D:\HTML\Sails\test\node_modules\sails-mongo\lib\index.js:268:21)
at D:\HTML\Sails\test\node_modules\machine\lib\private\help-build-machine.js:1514:39
at proceedToFinalAfterExecLC (D:\HTML\Sails\test\node_modules\parley\lib\private\Deferred.js:1153:14)
at proceedToInterceptsAndChecks (D:\HTML\Sails\test\node_modules\parley\lib\private\Deferred.js:913:12)
at proceedToAfterExecSpinlocks (D:\HTML\Sails\test\node_modules\parley\lib\private\Deferred.js:845:10)
at D:\HTML\Sails\test\node_modules\parley\lib\private\Deferred.js:303:7
at D:\HTML\Sails\test\node_modules\machine\lib\private\help-build-machine.js:952:35
at Function.handlerCbs.error (D:\HTML\Sails\test\node_modules\machine\lib\private\help-build-machine.js:742:26)
at connectCb (D:\HTML\Sails\test\node_modules\sails-mongo\lib\private\machines\create-manager.js:130:22)
at connectCallback (D:\HTML\Sails\test\node_modules\mongodb\lib\mongo_client.js:428:5)
at D:\HTML\Sails\test\node_modules\mongodb\lib\mongo_client.js:335:11
at processTicksAndRejections (internal/process/task_queues.js:79:11)
error: Could not load Sails app.
error:
error: Tips:
error: • First, take a look at the error message above.
error: • Make sure you've installed dependencies with `npm install`.
error: • Check that this app was built for a compatible version of Sails.
error: • Have a question or need help? (http://sailsjs.com/support)
/config/datastores.js
module.exports.datastores = {
default: {
adapter: "sails-mongo",
url: "mongodb://root#localhost/datab",
},
};
config/models.js
module.exports.models = {
schema: true,
migrate: "alter",
attributes: {
createdAt: { type: "number", autoCreatedAt: true },
updatedAt: { type: "number", autoUpdatedAt: true },
id: { type: "string", columnName: "_id" },
deleted: { type: "boolean", defaultsTo: false },
},
dataEncryptionKeys: {
default: "t9AkMiCRfZeODiZKQsgGif2zsE40wKJK6Uudr51L4hU=",
},
cascadeOnDestroy: true,
};
Could you try:
module.exports.datastores = {
default: {
adapter: require("sails-mongo"),
url: "mongodb://root#localhost/datab",
},
};

Apollo type defs ignored

I've made a basic implementation of ApolloClient:
const gqlClient = new ApolloClient({
connectToDevTools: true,
link: new HttpLink({
uri: "/api",
}),
cache: new InMemoryCache(),
resolvers: {
Group: {
icon: () => "noIcon",
},
},
typeDefs: gql`
extend type Group {
icon: String!
}
`,
});
The only fancy thing is the one resolver and type def - both of which are to support an icon field for groups (an upcoming feature).
I then try to query the server with the following:
gqlClient.query({
query: gql`{
groups {
name
icon
}
}`,
})
.then(console.log);
and get a big 'ol error:
bundle.esm.js:63 Uncaught (in promise) Error: GraphQL error: Cannot query field `icon' on type `Group'.
at new ApolloError (bundle.esm.js:63)
at bundle.esm.js:1247
at bundle.esm.js:1559
at Set.forEach (<anonymous>)
at bundle.esm.js:1557
at Map.forEach (<anonymous>)
at QueryManager../node_modules/apollo-client/bundle.esm.js.QueryManager.broadcastQueries (bundle.esm.js:1555)
at bundle.esm.js:1646
at Object.next (Observable.js:322)
at notifySubscription (Observable.js:135)
Running the same query without asking for icon works perfectly. I'm not quite sure what I'm doing wrong. How can I mock icon and fix this error?
I'm only running Apollo Client - do I need to run Apollo Server to get all of the features? The outgoing request doesn't seem to have any of my type def information, so I'm not sure how the having Apollo server would make a difference.
Handling #client fields with resolvers
gqlClient.query({
query: gql`
{
groups {
name
icon #client
}
}
`,
});

Cloud function fails after changing Runtime to Node.js 10

I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:
Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined
Detailed error log:
2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"
labels: {…}
logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2020-05-27T05:31:31.171084310Z"
resource: {…}
severity: "ERROR"
textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
at Array.forEach (<anonymous>)
at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28)
at process._tickCallback (internal/process/next_tick.js:68:7)"
timestamp: "2020-05-27T05:31:21.820Z"
trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}
My index.js is as below:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
process.env.GCLOUD_PROJECT,
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
// Leave collectionIds empty to export all collections
// or define a list of collection IDs:
// collectionIds: ['users', 'posts']
collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
})
.then(responses => {
const response = responses[0];
console.log(`Operation Name: ${response['name']}`);
return response;
})
.catch(err => {
console.error(err);
});
};
I had the same issue. I fixed it by changing:
process.env.GCLOUD_PROJECT
to my actual Project ID (e.g. "my_app_37274")
I had the same issue, It seems like in previous versions we don't need to GCLOUD_PROJECT in environment variable i.e it automatically detects it, but from node 10 onwards we need to pass this explicitly.
That's how I resolved it.
So instead of hardcoding it, try passing GCLOUD_PROJECT in cloud functions environment variables.
Note: GCLOUD_PROJECT is project id, not the project name.

gatsby-source-stripe develop errors

i want to gatsby stripe serverless checkout , i added products on stripe. but i cant install gatsby-source-stripe or gatsby-source-stripe-products. error;
error UNHANDLED EXCEPTION
Error: /...../node_modules/gatsby-source-stripe/gatsby-node.js:4
exports.sourceNodes = async ({ actions }, { objects = [], secretKey = "" }) => {
^^^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer
gatsby-config
{
resolve: `gatsby-source-stripe`,
options: {
objects: [
'balance',
'customers',
'products',
'applicationFees',
'skus',
'subscriptions'
],
secretKey: process.env.STRIPE_SECRET
}
},
i have .env file.
Make sure you have entered test SKUs in Stripe - you can do so by toggling the View test data.

Node Js and Ebay api

I am novice to NodeJs and working with ebay-api.
I found this great example at GitHub
one strange issue is when I run the js file via CMD. it is working but sometimes it shows error and then I cleared cache it works and sometimes after clearing the cache it shows error. But the code is exactly the same which I got output correctly. Did anyone face the same issue or any idea where might be the problem?
var ebay = require('../index.js');
var params = {
keywords: ["Canon", "Powershot"],
// add additional fields
outputSelector: ['AspectHistogram'],
paginationInput: {
entriesPerPage: 10
},
itemFilter: [
{name: 'FreeShippingOnly', value: true},
{name: 'MaxPrice', value: '150'}
],
domainFilter: [
{name: 'domainName', value: 'Digital_Cameras'}
]
};
ebay.xmlRequest({
serviceName: 'Finding',
opType: 'findItemsByKeywords',
appId: '<your app id>', // FILL IN YOUR OWN APP KEY
params: params,
parser: ebay.parseResponseJson // (default)
},
// gets all the items together in a merged array
function itemsCallback(error, itemsResponse) {
if (error) throw error;
var items = itemsResponse.searchResult.item;
console.log('Found', items.length, 'items');
for (var i = 0; i < items.length; i++) {
console.log('- ' + items[i].title);
console.log('- ' + items[i].galleryURL);
console.log('- ' + items[i].viewItemURL);
}
}
);
I'm getting the following errors:
C:\node_modules\ebay-api\examples> node H:\NodeJs\app.js //Run via NodeJS CMD
H:\NodeJs\app.js:36
if (error) throw error;
^
Error
at Request._callback (C:\Users\shiva raju\node_modules\ebay-api\lib\xml-request.js:151:23)
at Request.self.callback (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:200:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:194:7)
at Request. (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:1067:10)
at emitOne (events.js:101:20)
at Request.emit (events.js:191:7)
at IncomingMessage. (C:\Users\shiva raju\node_modules\ebay-api\node_modules\request\request.js:988:12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
Your suggestions would be appreciated. Thanks
You can use this node module ebay-node-api where you can get the response data in form of JSON.
You can check this example to check how to consume ebay-node-api
https://github.com/pajaydev/ebay-node-api/
You are throwing an error object in the callback but you are not catching it anywhere in the code. Please handle the error you are throwing.

Categories