How to call parent's method when requiring child class? - coffeescript

I have the following hierarchy:
class BaseController
validateCloverToken: ->
console.log 123
module.exports = new class RetailersController extends BaseController
getAll: (req, reply) ->
#validateCloverToken()
When I try to call RetailersController in another file:
RetailersController = require("../controllers/retailers")
RetailersController.getAll()
I get the following exception:
TypeError: Uncaught error: this.validateCloverToken is not a function
Any ideas how to fix this?
I am using it within a HapiJS route:
{
method: "GET"
path: "/retailers"
handler: RetailersController.getAll
config:
auth:
strategy: "jwt"
scope: ["a"]
description: "Get a list of all retailers"
tags: ["api"]
}

The code does not work here with HapiJS. "this" was the HapiJS context. When I use a fat arrow for the getAll function everything works fine.
It should look like:
getAll: (req, reply) =>
#validateCloverToken()

Related

Calling AxiosRef with method and data as empty object not working

I am working in a Nest TypeScript work where I would like to call a http request using AxiosRefby passing the method.
Means instead of calling as this.httpService.axiosRef.get(url, {headers}) I would like to invoke as this.httpService.axiosRef({method, url, headers}).
And there I am seeing some issue:
Here is my working code snippet:
async request<T = any>(creds: CredentialObj, method: Method, data: any, query?: Record<string, string>): Promise<T> {
const headers = this.getHeaders(creds);
const timeout = +(process.env.HTTP_CALL_TIMEOUT || 10000);
const url: string = `<the URL>`;
return this.httpService
.axiosRef.get(url, { headers })
.then((response: AxiosResponse<T>) => this.handleHttpResponse(response))
.catch((error: AxiosError) => this.handleHttpReject(error));
}
But If I change the axiosRef like this:
console.log(`Method: ${method}`);
console.log(`Data: ${JSON.stringify(data)}`);
return this.httpService
.axiosRef({ method, url, headers, data})
.then((response: AxiosResponse<T>) => this.handleHttpResponse(response))
.catch((error: AxiosError) => this.handleHttpReject(error));
It does not work and gives an error:
Method: get
Data: {}
Error: Request failed with status code 400
at createError (..\node_modules\axios\lib\core\createError.js:16:15)
at settle (...\nest-services\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\pradipm\clients\CloudManager\cm_12\occm\service-infra\nest-services\node_modules\axios\lib\adapters\http.js:260:11)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
It's just an empty data object.
Actually I want to make it like this way of passing the method name such that I can use it for all REST API verbs as a common util routine. For cases other than get (e.g. post, patch) we need to pass the payload. Hence trying to make a single utility for the same.
My axios version is: "axios": "^0.21.1",

Loopback4 with Mongodb authentification status code 500 error

i have been struggling with Loopback4 for days...Lb3 was so much easier...
my goal is to authenticate all of my routes except #get route.
configuration went well and when i tried to get route i got a message that route is authenticated, so i have put authenticate.skip(), and then got 500 status code:
ResolutionError: The key 'dataSources.mongoDS' is not bound to any value in context
It's probably a simple solution but i cannot find it...
my code is:
i have imported components in application.ts
this.component(AuthenticationComponent)
this.component(JWTAuthenticationComponent)
this.dataSource(MongoDsDataSource, UserServiceBindings.DATASOURCE_NAME)
this.bind(UserServiceBindings.USER_SERVICE).toClass(MyUserService);
this is my datasource code:
const config = {
name: 'mongoDS',
connector: 'mongodb',
url: '',
host: 'localhost',
port: 27017,
user: '',
password: '',
database: 'ropesdb',
useNewUrlParser: true
};
#lifeCycleObserver('datasource')
export class MongoDsDataSource extends juggler.DataSource
implements LifeCycleObserver {
static dataSourceName = 'mongoDS';
static readonly defaultConfig = config;
constructor(
#inject('dataSources.config.mongoDS', {optional: true})
dsConfig: object = config,
) {
super(dsConfig);
}
}
and this is my repository code:
export class RopeRepository extends DefaultCrudRepository<
Rope,
typeof Rope.prototype.id,
RopeRelations
> {
constructor(
#inject('dataSources.mongoDS') dataSource: MongoDsDataSource,
) {
super(Rope, dataSource);
}
}
I believe LoopBack uses the datasource filename to determine the name of the datasource and place the name in the context. For example, [name-in-kebab-case].datasource.ts will be datasource.NameInCamelCase in the context. Is MongoDsDataSource placed in mongo-ds.datasource.ts?

allure.createAttachment exception error - Cannot read property 'currentStep' of undefined

I can successfully add screenshots to allure reports, but i get the following exception error:
error:
TypeError: Cannot read property 'currentStep' of undefined
at Allure.addAttachment (/Users//xxx/xxx/xxx/node_modules/allure-js-commons/index.js:86:45)
at Allure.createAttachment (/Users/xxx/xxx/xxx/node_modules/allure-js-commons/runtime.js:48:29)
at /Users/xxx/xxx/xxx/lib/class/class-name.js:30:20
at process._tickCallback (internal/process/next_tick.js:68:7)
class:
browser.takeScreenshot().then(function (png) {
allure.createAttachment(title, new Buffer(png, 'base64'));
}).catch((error: any) => console.log(error));
const allure = require('mocha-allure-reporter');
allure is a global identifier, injected by reporter to your code.
Add the following line to the top of your file to tell Typescript about it
declare const allure: any;
I think createAttachment requires a callback function and not a buffer being passed directly.
Can you try changing your code to reflect the following
browser.takeScreenshot().then(function (png) {
allure.createAttachment('Screenshot', function () {
return new Buffer(png, 'base64')
}, 'image/png')()
}).catch((error: any) => console.log(error));

sails helpers and machine spec

I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing

How to make POST call using FOSRestBundle

I am trying to setup a RESTFUL web service using FOSRestBunble, but I have some problem making POST calls, here's my setup:
app/config/routing.yml
rest:
type: rest
resource: "routing_rest.yml"
prefix: /api
app/config/routing_rest.yml
Rest_User:
type: rest
resource: "#AppBundle/Resources/config/routing_rest.yml"
AppBundle/Resources/config/routing_rest.yml
rest_application:
type: rest
resource: "AppBundle:Rest"
name_prefix: api_
AppBundle/Controller/RestController.php
class RestController extends FOSRestController
{
public function testrestAction(Request $request)
{
$r = [
'is' => 'TEST'
];
return $r;
}
public function getArticleAction()
{
$r = [
'is' => 'GET'
];
return $r;
}
public function postArticleAction()
{
$r = [
'is' => 'POST'
];
return $r;
}
}
I also made PUT and DELETE test methods. so when I do some test call
GET /api/testrest
{
"is": "TEST"
}
GET /api/article
{
"is": "GET"
}
POST /api/article
No route found for "POST /api/article": Method Not Allowed (Allow: GET, HEAD) (405 Method Not Allowed)
PUT and DELETE are also fine. Am I missing some configuration?
second problem: if I make a API folder inside Controller folder, I change the namespace for RestController to "namespace AppBundle\Controller\API;" and I update "AppBundle/Resources/config/routing_rest.yml" to
resource: "AppBundle:API:Rest"
then I got this message:
Can't locate "AppBundle:API:Rest" controller in /var/www/ws/app/config/routing_rest.yml (which is being imported from "/var/www/ws/app/config/routing.yml").
any help appreciated
1-option, run app/console debug:router (or bin/console debug:router if v > 2.8), to list generated routes;
2-option, add RouteResource annotation to class (eg. article), rename postArticleAction to postAction and check POST /api/articles is responding or not;
3-option, add article url explicitly with #POST annotation, eg. /** #Post("article") */