https://github.com/davebryson/meteor_file_upload_example
the above is the original code using Meteor.router
and i wanted to convert this code only using iron-router, instead of previous router package
but the problem is when i upload file,
i can't understand how to convert these code using iron-router api.
i think there's a problem with index.html and serverside main.js code but i can't fix that.
would you please convert this code below using iron router plz?
in serverside main.js in the original code.
Meteor.Router.configure(
{
bodyParser:
{
uploadDir: 'uploads',
hash: 'sha1',
keepExtensions : true
}
}
);
Meteor.Router.add('/upload/file', 'POST',
function()
{
var title = this.request.body.fileTitle,
size = this.request.files.fileInfo.size,
path = this.request.files.fileInfo.path,
name = this.request.files.fileInfo.name,
obj = {title: title, size: size, path: path, name: name};
Files.insert(obj);
// redirect to root
return [301, {Location: '/'}, ""]
}
);
and i'v already converted the code in clientside main.js like below
Router.map(function () {
this.route('listFiles', {path: '/'});
this.route('addFile', {path: '/add'});
});
Template.listFiles.helpers({
list: function () {
return Files.find({});
}
});
Template.listFiles.events({
'click #addFileBtn' : function(e) {
e.preventDefault();
Router.go('/add');
}
});
Template.addFile.events({
'click #cancelBtn': function(e){
e.preventDefault();
Router.go('/');
}
});
Meteor.subscribe("files");
the point is that i can't handle how to use http method in serverside code with iron-router
Meteor now directly allows you to attach middleware to the server using the WebApp package, with standard Connect handlers.
Put webapp inside .meteor/packages of your app. You can then attach middleware to WebApp.connectHandlers inside your app. It's not too well documented yet, but treat it as a normal connect server.
Related
I am using glue to spin up the hapi server so I gave the json object with connection and registration details.
I have 10 routes and i need to use authentication strategy for all the 10 routes, So followed the below steps
1) I have registered the xyz custom auth plugin
2) Defined the strategy server.auth.strategy('xyz', 'xyz', { });
3) At every route level I am enabling auth strategy
auth: {
strategies: ['xyz'],
}
How can I give below line to glue configuration object itself.
server.auth.strategy('xyz', 'xyz', { });
Glue.compose(ServerConfig, { relativeTo: baseDir }, (err, server) => {
internals.server = server;
})
One more question here is, in this line server.auth.strategy('xyz', 'xyz', { from json file}); I am reading the JSON data from a config file. When I change the data in this JSON file I dont want to restart the server manually to load the modified data. Is there any plugin or custom code to achieve this?
I figured out a general workaround for when you want to do setup that Glue does not directly support (AFAIK) and you also don't want to keep adding to index.js.
Create a plugins folder where your manifest.js is located.
Create a file plugins/auth.js (in this case). Here you will have a register callback with access to the server object and you can make setup calls that go beyond what Glue does declaratively.
Add a plugin item to manifest.js pointing to your plugin file.
in manifest.js:
register: {
plugins: [
{
plugin: './plugins/auth',
},
]
}
in plugins/auth.js:
module.exports = {
name: 'auth',
async register (server) {
await server.register([
require('#hapi/cookie'),
]);
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: '!wsYhFA*C2U6nz=Bu^%A#^F#SF3&kSR6',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await users.find(
(user) => (user.id === session.id)
);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});
server.auth.default('session');
},
};
(auth setup code is from the Hapi docs at enter link description here)
This is the way I have found where I can call things like server.auth.strategy() sort-of from manifest.js.
Note: Auth is not a great example for this technique as there is a special folder for auth strategies in lib/auth/strategies.
I am trying to pre-cache some of my static app shell files using service worker. I can't use 'sw-appcache' as I am not using any build system. However, I tried using 'sw-toolbox' but I am not being able to use it for pre-caching.
Here is what I am doing in my service worker JS:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('gdvs-static').then(function(cache) {
var precache_urls = [
'/',
'/?webapp=true',
'/css/gv.min.css',
'/js/gv.min.js'
];
return cache.addAll(precache_urls);
});
);
});
I've also tried this:
importScripts('/path/to/sw-toolbox.js');
self.addEventListener('install', function(event) {
var precache_urls = [
'/',
'/?webapp=true',
'/css/gv.min.css',
'/js/gv.min.js'
];
toolbox.precache(precache_urls);
});
Here is the URL of my app: https://guidedverses-webapp-staging.herokuapp.com/
Here is the URL of my service worker file: https://guidedverses-webapp-staging.herokuapp.com/gdvs-sw.js
What am I missing?
Silly me. I forgot to add the fetch handler into my service worker. I thought it works like appchache and automatically returns the cached data when matches with the cache URL. I underestimated the power of Service Worker. Following code did the trick for me.
this.addEventListener('fetch', function(event) {
console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
I have a mixed Ember/Rails app with a Rails route in the API namespace to take any single Event and convert it to an .ics file for import into a user's calendar (a la this question). Ember is running with the command ember server --proxy http://localhost:3000, which is connecting it to the Rails server process.
The below snippets illustrate my setup:
Rails routes.rb snippet:
namespace :api do
# snip
resources :events do
# snip
get 'export_event_ical', on: :member
end
end
Rails events_controller.rb snippet:
def export_event_ical
#event = Event.find(params[:id])
#calendar = Icalendar::Calendar.new
ical_event = Icalendar::Event.new
ical_event.dtstart = #event.start.strftime("%Y%m%dT%H%M%S")
ical_event.dtend = #event.start.strftime("%Y%m%dT%H%M%S")
ical_event.summary = #event.body.truncate(50)
ical_event.description = #event.body
# event.location = #event.location
#calendar.add_event ical_event
#calendar.publish
headers['Content-Type'] = "text/calendar; charset=UTF-8"
render :text => #calendar.to_ical
end
So, for example, in my Ember/Handlebars index template, if I have an event parameter that references a single Event, I can use Export to iCal to reach the API route that Rails is providing (i.e., skipping Ember on port 4200 and talking to Rails at 3000).
So far so good. But how do I make this into a dynamic Ember-controlled link that is routed through Ember to Rails?
I've tried a few things that don't work:
Adding a route to the Ember events resource (router.js):
this.resource('events', function() {
this.route('show', {path: ':event_id'});
this.route('export_to_ical', {
path: '/api/events/:event_id/export_event_ical'
});
});
Adding some goofball jQuery to the events.js route as a button action and using <button {{action 'exportToICal' event.id}}>Export to iCal</button> in my template:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
exportToICal: function(eventID) {
$.get('/api/events/' + eventID + '/export_event_ical',
function(){
alert('Got here.');
});
}
}
});
Reading some docs:
http://guides.emberjs.com/v1.10.0/components/sending-actions-from-components-to-your-application
EmberJS - How to dynamically generate link with linkTo?
How are you supposed to do this in Ember?
In my app I use the environment to declare server endpoints, sort of like in rails, at the bottom:
/* jshint node: true */
'use strict';
var extend = require('util')._extend;
module.exports = function(environment, appConfig) {
var ENV = extend(appConfig, {
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
});
if (environment === 'development') {
ENV.serverHost = 'http://localhost:3000';
}
return ENV;
};
Then you can grab the value like this
var config = this.container.lookup('config:environment');
var url = config.serverHost + "/...";
I'm currently working on an app with a server that uses Hapi, and I am running into a problem whenever I try to load a .jade file. Here is the current code for my index.js file:
var Hapi = require('hapi');
var internals = {};
internals.main = function() {
var options = {
views: {
engines: { jade: 'jade' },
path: '../app',
compileOptions: {
pretty: true
}
}
};
this._server = new Hapi.createServer('localhost', 8000, options);
this._server.route({
method: 'GET',
path: '/',
handler: function(request, reply) {
reply.view('index')
}
});
// Start server.
this._server.start()
};
internals.main();
The file has a series of local scripts and CSS files that are in the app directory, but when the page index.jade is loaded, it does not see those local files. Is there something I need to add/modify in my options, or is this location of local scripts and style files a problem with jade compilation using Hapi?
I was looking for a similar solution, while trying to setup a single page application with angular.js and hapi.js
I have found that adding the configuration below to your server routes will help to make CSS, JS, ... files in '/public' directory visible to the application.
server.route({
method: "GET",
path: "/public/{path*}",
handler: {
directory: {
path: "./public",
listing: false,
index: false
}
}
});
Hope it helps.
I have a web application that uses requirejs to load its modules. The web applications works without problems in any desktop browser, it also works on iOS and Android when packaged with Cordova. Does however NOT work when building a Windows Phone 8 Cordova application.
I get the following error:
"View Not Found: Searched for "views/shell" via path "text!views/shell.html"
(I'm using Durandal)
I have the following application structure:
lib/require/require.js
www/app/viewmodels/shell.js
www/app/views/shell.html
www/app/main.js
www/index.html (contains line: )
:
www/app/main.js contains the following code:
requirejs.config({
//baseUrl: 'x-wmapp0:www/app',
baseUrl: 'app',
enforceDefine: true,
paths: {
'text': '../lib/require/text',
'durandal':'../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '../lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-2.3.0',
'bootstrap': '../lib/bootstrap3/js/bootstrap',
'jquery': '../lib/jquery/jquery-1.9.1',
'modules' : 'modules'
},
shim: {
'bootstrap': {
deps: ['jquery'],
exports: 'jQuery'
}
}
});
define(['durandal/system', 'durandal/app', 'durandal/viewLocator', 'bootstrap'], function (system, app, viewLocator, bootstrap) {
//>>excludeStart("build", true);
system.debug(true);
//>>excludeEnd("build");
app.title = 'MyApp';
app.configurePlugins({
router: true,
dialog: true,
widget: true
});
app.start().then(function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention('viewmodels', 'views', 'views');
//Show the app by setting the root view model for our application with a transition.
app.setRoot('viewmodels/shell', 'entrance', 'applicationHost');
});
});
This code works perfectly on all devices except WP8. I tried the line baseUrl: 'x-wmapp0:www/app' to set the actual path used internally by WP8 Cordova, but that does not work. Is that because it is not a path starting with '/' or http?
Any ideas on how to configure requirejs to be able to load modules and views using requirejs?
See if this is any help to you http://mikaelkoskinen.net/durandal-phonegap-windows-phone-8-tutorial/
Also, as of the 18th October 2013, Phonegap Build has added beta support for WP8. Add "winphone: as the gap:platform and ensure you're using phonegap 3.0. We're currently having no luck but maybe you can use that.
I just solve this problem for myself as well, what I ended up doing was waiting for the deviceloaded event before I loaded my main.js.
Cordova applies a patch to XMLHttpRequest which has been applied when deviceloaded has been triggered.
In my app I it ended up looking similar to this:
<script src="js/require.js"></script>
<script>
document.addEventListener('deviceloaded', function() {
var script = document.createElement('script');
script.src = 'js/main.js';
document.body.appendChild(script);
}, false);
</script>
I hope that works out for you as well!
One other thing, I noticed in my app that if I try to load weinre I couldn't get my app started at all with require.js. I haven't been able to research this further yet though.
I recommend to set a breakpoint to cordovalib/XHRHelper.cs HandleCommand method and see what is going on. Also the following version of HandleCommand could work better for you
public bool HandleCommand(string commandStr)
{
if (commandStr.IndexOf("XHRLOCAL") == 0)
{
string url = commandStr.Replace("XHRLOCAL/", "");
Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);
try
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoFile.FileExists(uri.AbsolutePath))
{
using (
TextReader reader =
new StreamReader(isoFile.OpenFile(uri.AbsolutePath, FileMode.Open, FileAccess.Read))
)
{
string text = reader.ReadToEnd();
Browser.InvokeScript("__onXHRLocalCallback", new string[] { "200", text });
return true;
}
}
}
url = uri.AbsolutePath;
}
catch { }
var resource = Application.GetResourceStream(new Uri(url, UriKind.Relative)) ??
// for relative paths and app resources we need to add www folder manually
// there are many related issues on stackoverflow + some prev worked sample don't because of this
Application.GetResourceStream(new Uri("www/" + url, UriKind.Relative));
if (resource == null)
{
// 404 ?
Browser.InvokeScript("__onXHRLocalCallback", new string[] { "404" });
return true;
}
else
{
using (StreamReader streamReader = new StreamReader(resource.Stream))
{
string text = streamReader.ReadToEnd();
Browser.InvokeScript("__onXHRLocalCallback", new string[] { "200", text });
return true;
}
}
}
return false;
}