create typeahead view on demand
authorDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 9 Jan 2013 23:34:25 +0000 (00:34 +0100)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 9 Jan 2013 23:34:25 +0000 (00:34 +0100)
angular-server.pl

index d65215b..9ed7925 100755 (executable)
@@ -186,6 +186,33 @@ get '/:database/_design/:design/_view/:view' => sub {
        }
        warn "CouchDB proxy $url";
        my $json = _couchdb_get($url);
+
+       if ( exists $json->{error} ) {
+               warn "creating CouchDB view because of ", dump($json);
+               my $url = "/" . $self->param('database') . "/_design/registration";
+               _couchdb_put $url, {
+                       _id => '_design/registration',
+                       language => 'javascript',
+                       views => {
+                               organizations => {
+                                       map    => q| function(doc) {
+if ( doc.user.organization != '' ) {
+  emit(doc.user.organization, 1);
+  if ( doc.user.persons ) {
+    doc.user.persons.forEach( function(person) {
+      emit(person.organization, 1);
+    });
+  }
+}
+                                       }q|,
+                                       reduce => q| function(keys,values,rereduce) { return sum(values); } |,
+                               }
+                       }
+               };
+               $json = _couchdb_get($url)
+               || die "give up!";
+       }
+
        if ( $format eq 'key_array' ) { # array of keys sorted by value
                $json->{rows} = [ map { $_->{key} } sort { $b->{value} <=> $a->{value} } @{ $json->{rows} } ];
        }