Strongloop - Execute PHP with model.js - javascript

I'm trying to execute PHP within a loopback model. When visiting myapi:3000/api/Door/open I'd like it to run the PHP file containing a function.
I have the /Door/open added as a remote method and it shows up in swagger.ui, the api returns "message": "createElement is not defined", even though jquery is included.
Here is my doors.js showing the remote method setup:
module.exports = function(Door) {
Door.open = function(id, cb) {
var script = createElement('script');
script.src = 'http://code.jquery.com/jquery-2.1.4.min.js';
script.type = 'text/javascript';
getElementsByTagName('head')[0].appendChild(script);
$.ajax({
url: "http://192.168.10.139/Facility/doorfunc_dynamic.php?dpip=192.168.10.249&doorid=3&func=unlock"
}).done(function(data) {
console.log(data);
});
};
Door.remoteMethod(
'open',
{
description: 'Open a door by id',
accepts: {args: 'id', type: 'number', name: 'id', description: 'Door id'},
returns: {arg: 'open', type: 'string'},
http: {path: '/open', verb: 'get'}
}
);
};
Does anyone know how to resolve this?
I have tried adding a static page within the client folder, however it does not show within the swagger.ui explorer.

If you want to perform only http request, you can use request package.
var request = require('request');
module.exports = function(Door) {
Door.open = function(id, cb) {
request('http://192.168.10.139/Facility/doorfunc_dynamic.php?dpip=192.168.10.249&doorid=3&func=unlock',
function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
};
Door.remoteMethod(
'open',
{
description: 'Open a door by id',
accepts: {args: 'id', type: 'number', name: 'id', description: 'Door id'},
returns: {arg: 'open', type: 'string'},
http: {path: '/open', verb: 'get'}
}
);
};
Hope it solves your problem.

Related

Make the code take one number at a time and embed in it

I'm trying to use an API in my code that downloads media from Instagram posts.
The response passed by the API is as follows:
{
post1: {
url: 'download url',
type: 'media type'
},
post2: {
url: 'download url',
type: 'media type'
}
}
post1, post2, and so on depending on the number of posts on that link (up to 10 posts).
i would like it to query and get the url of each of them.
var resultsMedia = await apis.insta_post(link)
I tried
resultsMedia.post[i].url
(i refers to a for function I tried, for var i = 1; ...)
and I was not successful.
I would like to know how I could make the resultsMidia.post
take one number at a time
example: resultsMedia.post1.url, resultsMedia.post2.url, resultsMedia.post3.url, and so on.
(resultsMedia refers to the API call, post refers to the api response, and url is a parameter also present in the API response)
You can iterate using Object.entries():
const response = {
post1: {
url: 'download url 1',
type: 'media type'
},
post2: {
url: 'download url 2',
type: 'media type'
}
}
Object.entries(response).forEach(([post, data]) => {
console.log('---------------')
console.log('Post:', post)
console.log('Post number:', +post.replace('post', ''))
console.log('Data:', data)
console.log('Data url:', data.url)
console.log('---------------')
})
You can try this:
const postCount=Object.keys(resultsMedia).length;
for (let i = 1;i<=postCount;i++){
console.log(resultsMedia[`post${i}`])
}

yajra datatable on server side accessing API to laravel passport generates randomly error 401

Currently I'm developing an ajax to load yajra datatables by server side in laravel 5.7 framework (env: XAMPP Apache 2.4.6 and PHP 7.3.0). If I gently perform a click each page or gently input on string search, then It's okay on its behavior while loading/processing.
However, randomly errors 401 when I rapidly click those buttons either quickly enter text in search box. I think the root cause is the multiple ajax call occurs when I did that, but not sure.
So this is my codes:
javascript in blade.php:
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#tblpropinsi').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('home.user.list') }}",
dataType: 'json',
type: "GET"
},
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'description', name: 'description'},
]
});
});
controller.php
// Trial API
public function homeuserlist(Request $request)
{
try {
// API Access
$response = $this->client->request('GET', '/api/user/list', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer eYjblablabla..',
],
'query' => array_merge(
[
'type' => 'table',
'col' => 'id',
'findstr' => '%',
],
$request->all() // yajra serverside query
),
]);
}
catch (RequestException $e) {
return response(['error' => 'API failed'], 401);
}
return json_decode($response->getBody(), true);
}
Need your kind help
Regards

Loopback mock session

I'm using loopback with express session to store cartId.
But I need to inject cartId on request session in order to make my tests work.
So on my remote method I have
Cart.get = function (req, cb) {
Service.getCart(req, req.session.cartId)
.then(function (result) {
cb(null, result);
})
.catch(cb);
};
Cart.remoteMethod(
'get',
{
accepts: { arg: 'req', type: 'object', 'http': { source: 'req' } },
returns: { arg: 'cart', type: 'object', root: true },
http: { path: '/', verb: 'get' }
}
);
How can I force req.session.cartId for my tests?
Thanks
If I understand your case correctly, you can do something similar to the code below, you would just add another param (cardId) to your get method definition:
Cart.remoteMethod('get',{
accepts: [
{ arg: "caseId", type: "number", http: {source:'path'} },
{ arg: 'req', type: 'object', http: { source: 'req' } }
],
returns: { arg: 'cart', type: 'object', root: true },
http: { path: '/:caseId/getCart', verb: 'get' }
});
You can simply use "get" remote method and pass cartId through URL or if you have concern about cartId visibility on URL then you can use post method as following code.
Use following cart.js file and explore in loopback api.
module.exports = function (Cart) {
Cart.getCart = function (cartId, cb) {
Cart.findOne({
where: { cartId : cartId }
}, function (err, cart) {
cb(null, users);
});
};
Cart.remoteMethod('getCart', {
accepts: {
arg: "id",
type: "string",
required: true
},
returns: {
arg: 'cart',
type: 'object'
},
http: {
path: '/:cartId/getcart',
verb: 'get'
}
});
};
get call : http://HOST:IP/cart/YourID/getcart
You will retrieve cart by Id.
Hope this will work.

While Dynamically loading Treestore using Ajax proxy child nodes arent appearing

I want load a Treestore using ajax proxy.But it shows only root node in user interface.
Json coming from server as response looks correct and no error in console.
I want to load the root node also from server side response but though json appears correct it doesnt appear in the user interface.
{"result":{"text":"ABC","leaf":false,"expanded":true,"children":[{"text":"Dashboard","leaf":false,"expanded":false},{"text":"Report","leaf":false,"expanded":false},{"text":"Chart","leaf":false,"expanded":false}]}}
var model=Ext.define('TreeModel',{
extend:'Ext.data.Model',
fields:[{
name:'text',
type:'string'
},
{
name:'leaf',
type:'boolean'
},
{
name:'expanded',
type:'boolean'
}],
proxy: {
type: 'ajax',
url: 'FetchTreeChidren',
reader: {
type: 'json',
root: 'result'
}
}
});
var store = Ext.create('Ext.data.TreeStore', {
model:model
});
Ext.Ajax.request({
url: 'FetchTreeChidren',
params: {
level:'level1'
},
async:false,
success: function(response){
var treejson = Ext.JSON.decode(response.responseText);
store.setRootNode(treejson);
}
});
var lefttree=Ext.create('Ext.tree.Panel', {
region:'west',
height:screen.height-150,
title: 'Simple Tree',
width: 200,
height: 150,
store: store,
rootVisible: false,
renderTo: Ext.getBody()
});
return lefttree;
please help me out.
Thanks & Regards
Try to use
var store = Ext.create('Ext.data.TreeStore', {
model:model
proxy: {
type: 'memory'
},
root: {
expanded: false,
children: childreanArr
}
});
and change
store.reconfigure(treejson);
inside the success. This work for me

How do you autopublish with FB.UI?

I have the stream_publish permission but it still pops up a dialog and there doesn't seem to be any way to pass in an autopublish bool (like it was before the graph api).
EDIT: Also tried offline_access with stream_publish.
Any ideas on how to get this to work?
function streamPublish(imageUrl, imageHref, attachName, attachHref, attachCaption) {
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: attachName,
caption: attachCaption,
description: (
''
),
href: attachHref,
media: [
{
type: 'image',
href: imageHref,
src: imageUrl
}
]
}
},
function(response) {
if (response && response.post_id) {
//alert('Post was published.');
} else {
//alert('Post was not published.');
}
}
);
}
http://www.takwing.idv.hk/tech/fb_dev/jssdk/learning_jssdk_12.html
The following will autopublish if you have the permissions unlike FB.UI :)
function publishPost(session) {
var publish = {
method: 'stream.publish',
message: 'is learning how to develop Facebook apps.',
picture : 'http://www.takwing.idv.hk/facebook/demoapp_jssdk/img/logo.gif',
link : 'http://www.takwing.idv.hk/facebook/demoapp_jssdk/',
name: 'This is my demo Facebook application (JS SDK)!',
caption: 'Caption of the Post',
description: 'It is fun to write Facebook App!',
actions : { name : 'Start Learning', link : 'http://www.takwing.idv.hk/tech/fb_dev/index.php'}
};
FB.api('/me/feed', 'POST', publish, function(response) {
document.getElementById('confirmMsg').innerHTML =
'A post had just been published into the stream on your wall.';
});
};

Categories

Resources