I am using loopback in c9 ,basically i have 2 models
->file(that uploads a file )
->user(that has a remote method that updates values fetched from client )
I want to upload the file first and get the uploaded filename as it ll be used by the remote method to be updated in db(monodb).How can I access filename property in file model in user model without model relations. I tried the below code in "user.js"
`var loopback=require('loopback');
var file=loopback.getModel('file');
console.log(file.name);`
but it displays only "undefined".Is it wrong ?if so what's the way to access the filename ??
or should I use hooks?
The upload logic does not seem very clear to me, but if the question is exactly what you ask and is about accessing one model from another model in a remote hook, then you may find the answer here: Loopback documentation: Getting a reference to a model in JavaScript
To be more precise, in your user.js you may have something like this:
module.exports = function(User) {
User.beforeRemote('**', function(ctx, unused, next) {
var File = User.app.models.File;
...
});
}
Related
My use case needs me to use Dynamic Model attributes with my Sails.Js project and all of my methods fail. First I tried to call model1 method from model2 but it doesn't works. I also tried to use global variables but this fails too because, the global is set after the load of the application, and finaly I called model1Controller from the model2 but it still not working.
This is the mothod in my model2Controller
getbyTable:function(req,res){
let field = Field.find({fTable:req.param('tableName')});
field.exec(function(err, response) {
if(err) {
res.status(500);
return res.view('500', {data: err});
}
//res.json(response);
return response;
});
},
And this is my model2
'use strict';
const fieldController = require('../controllers/Model1Controller');
const donnees = fieldController.getbyTable('person');
module.exports={
}
When run it fires as error that req.param is not a function.
Need help!!! Thanks.
This looks like an interesting way to organize - I'd be curious to see how successful a project could be without Model attributes set in stone.
I can see a few specific errors in your code, maybe seeing them will help you move forward.
From your model2 you invoke getbyTable('person') with a string argument - but all controller methods are really intended to have reqest/response arguments (as in the definition getbyTable(req, res). Directly invoking a controller method is a bit unusual - if you ever did it, I'd expect to pass along a request and response from some other controller method.
Inside getbyTable, you try to return the response, but the response is only defined inside the exec callback. The response would be an array of objects fetched from your database - if that's what you need, you can't return them directly since database calls are async.
Your controller should probably do something with res in all logical branches, such as res.json, res.send, etc.
It's a bit hard to see exactly what you're trying to achieve, so maybe if you could explain the goal I could have some more relevant advice. For now, I could say that you might want to consider putting some code inside a service rather than a controller. Create file /api/services/MyService.js and use it to export a method that can be called from your model2 (you can require the service just like the controller). Keep the controller methods strictly for handling requests.
Good luck.
I want to re-configure AR session after session has been running. I want to change Augmented Images database.
I don't seem to find a way to set the reset the session configuration.
getSessionConfiguration(Session session)
This function only seems to be called once at the beginning.
Is there a way to re-configure? Should I not be using the fragment?
I make changes to my config on the fly. You can accomplish this by extending ARFragment and having access to the config or simply be accessing the ARFragment from your xml within your activity. Here is an example.
arSceneView.session?.apply {
val changedConfig = config
changedConfig.planeFindingMode = Config.PlaneFindingMode.HORIZONTAL_AND_VERTICAL
configure(changedConfig)
}
That's it, just call configure(myNewConfig) and it will update it for you.
Of course in this example, I get the current config, modify it and put it back, but you could replace it if preferred.
I have an index.html which contains my Elm app. The Elm app uses various GETs to an API served by the same server as the one that serves the index.html.
Rather than hardcode the URLs in my Elm code for the GETs, e.g.:
url =
"http://localhost:8080/api/tasks"
is there a function which returns the value of window.location.href?
I'd like to do something like:
url =
getHref() ++ "/api/tasks"
In this way, if I move my server to somewhere else I will not need to update all the urls in my Elm code.
Whilst the above answers your question, I think there is a more straightforward solution to the problem:
If the application code is being served from the same server (URL) as the API you want to access you don't need to specify the server - just the root relative path for your api i.e. you can make requests to /api/tasks from your elm code and the browser will sort out the rest for you.
This is how I addressed the problem in my deployed code.
There is elm-history package with the location function for this, but it's deprecated and doesn't exist for 0.18 version.
Then you might want to use elm-navigation package and explicitly store the current location in your model.
Please have a look at this example. A program with navigation can be created via:
Navigation.program UrlChange
{ init = init
, view = view
, update = update
, subscriptions = (\_ -> Sub.none)
}
UrlChange here is a type of message, which triggers on every url change, so you can process it and set the current location:
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UrlChange location ->
( { model | location = location }
, Cmd.none
)
And then purely get the location.href wherever the model is accessible.
In the provided application, this place is view: viewLocation model.location
In your application, it's, for example, something like this:
url model =
model.location.href ++ "/api/tasks"
Use URL Builder to link to anoter page on your site
There's no need to specify the base url:
import Url.Builder exposing (absolute)
url = absolute [ "api", "tasks" ] []
-- results in "http://localhost:8080/api/tasks"
-- if working in your developer environment
-- the URL will automatically change in production
-- to the correct URL assuming you don't have any crazy set ups
And you definitely will not need to worry if your server URL changes. So you can easily switch from a development to production/staging environments without any additional configuration.
I am having an issue trying to query the ScriptDb of a resource file in Google Apps Script. I create a script file (file1), add it as a resource to another script file (file2). I call file1 from file2 to return a handle to its ScriptDb. This works fine. I then try to query the ScriptDb but have a permissions error returned.
Both files owned by same user and in same google environment
See code below:
file 1:
function getMyDb() {
return ScriptDb.getMyDb;
}
file 2 (references file1):
function getDataFromFile1() {
var db = file1.getMyDb(); // This works
var result = db.query({..............}); // This results in a permissions error!
}
I am at a loss to understand why I can access file1 and get back a handle on the ScriptDb, but then am not able to query it, due to an permissions issue.
I have tried to force file1 to require re-authorization, but have not yet been successful. I tried adding a new function and running it, so any suggestions there would be gratefully received.
Thanks in advance
Chris
There appears to be an error in file1/line2. It says "return ScriptDb.getMyDb;" but it should say "return ScriptDb.getMyDb();"
If you leave out the ()s then when you call file1 as a library, file1.getMyDb() will return a function which you store in var db. Then the line var result = db.query({..............}) results in an error because there is no method "query" in the function.
Is that what's causing your error?
I have figured out what the problem was, a misunderstanding on my part regarding authorisation. I was thinking of it in terms of file permissions, when in fact that problem was that my code was not authorised to run the DbScript service. As my code calls a different file and receives back a pointer to a ScriptDb database it is not using the ScriptDb service, so then when it calls the db.query() it invokes the ScriptDb service, for which it is not authorised.
To resolve this I just had to create a dummy function and make a ScriptDb.getMyDb() call, which triggered authorisation for the service. The code then worked fine.
Thanks for the input though.
Chris
I am using the Microsoft Azure .NET client libraries to interact with Azure cloud storage. I need to be able to access additional information about each blob in its metadata collection. I am currently using CloudBlobDirectory.ListBlobs() method to get a list of blobs in a particular directory of a directory structure I've devised in the blob names. The ListBlobs() method returns a list of IListBlobItem objects. They only have a couple of properties: Url and references to parent directory and parent container. I need to get to the metadata of the actual blob objects.
I envisioned there would be a way to either cast the IListBlobItem to a BlockBlob object or use the IListBlockItem to get a reference to the BlockBlob, but can't seem to find a way to do that.
My question is: Is there a way to get a BlockBlob object from this method, or do I have to use a different way of getting the actual BlockBlob objects? If different, then can you suggest a way to achieve this, while also being able to filter by the "directory" scheme?
OK... I found a way to do this, and while it seems a little clunky and indirect, it does achieve the main thing I thought should be doable, which is to cast the IListBlobItem directly to a CloudBlockBlob object.
What I am doing is getting the list from the Directory object's ListBlobs() method and then looping over each item in the list and casting the item to a CloudBlockBlob object and then calling the FetchAttributes() method to retrieve the properties (including the metadata). Then add a new "info" object to a new list of info objects. Here's the code I'm using:
CloudBlobDirectory dir = container.GetDirectoryReference(dirPath);
var blobs = dir.ListBlobs(true);
foreach (IListBlobItem item in blobs)
{
CloudBlockBlob blob = (CloudBlockBlob)item;
blob.FetchAttributes();
files.Add(new ImageInfo
{
FileUrl = item.Uri.ToString(),
FileName = item.Uri.PathAndQuery.Replace(restaurantId.ToString().PadLeft(3, '0') + "/", ""),
ImageName = blob.Metadata["Name"]
});
}
The whole "Blob" concept seems needlessly complex and doesn't seem to achieve what I'd have thought would have been one of the main features of the Blob wrapper. That is, a way to expand search capabilities by allowing a query over name, directory, container and metadata. I'd have thought you could construct a linq query that would read somewhat like: "return a list of all blobs in the 'images' container, that are in the 'natural/landscapes/' directory path that have a metadata key of 'category' with the value of 'sunset'". There doesn't seem to be a way to do that and that seems to be a missed opportunity to me. Oh, well.
If I'm wrong and way off base here, please let me know.
This approach has been developed for Java, but I hope it can somehow be modified to fit any other supported language. Despite the functionality you ask has not been explicitly developed yet, I think I found a different (hopefully less clunky) way to access CloudBlockBlob data from a ListBlobItem element.
The following code can be used to delete, for example, every blob inside a specific directory.
String blobUri;
CloudBlobClient blobClient = /* Obtain your blob client */
try{
CloudBlobContainer container = /* Obtain your blob container */
for (ListBlobItem blobItem : container.listBlobs(blobPrefix)) {
if (blobItem instanceof CloudBlob) {
blob = (CloudBlob) blobItem;
if (blob.exists()){
System.out.println("Deleting blob " + blob.getName());
blob.delete();
}
}
}
}catch (URISyntaxException | StorageException ex){
Logger.getLogger(BlobOperations.class.getName()).log(Level.SEVERE, null, ex);
}
The previous answers are good. I just wanted to point out 2 things:
1) Nowadays ASYNC programming is recommended to do and supported by Azure SDK as well. So try to use it:
CloudBlobDirectory dir = container.GetDirectoryReference(dirPath);
var blobs = dir.ListBlobs(true);
foreach (IListBlobItem item in blobs)
{
CloudBlockBlob blob = (CloudBlockBlob)item;
await blob.FetchAttributesAsync(); //Use async calls...
}
2) Fetching Metadata in a separate call is not efficient. The code makes 2 HTTP request per blob object. ListBlobs() method supports getting Metadata with as well in one call by setting BlobListingDetails parameter:
CloudBlobDirectory dir = container.GetDirectoryReference(dirPath);
var blobs = dir.ListBlobs(useFlatBlobListing: true, blobListingDetails: BlobListingDetails.Metadata);
I recommend to use second code it it is possible. Since it is the most efficient way to fetch Metadata.