Skip to content

Total downloads user #740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 3, 2017
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions app/adapters/user.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({
stats(id) {
return this.ajax(this.urlForStatsAction(id), 'GET');
},

urlForStatsAction(id) {
return `${this.buildURL('user', id)}/stats`;
},

queryRecord(store, type, query) {
let url = this.urlForFindRecord(query.user_id, 'user');
return this.ajax(url, 'GET');
Expand Down
5 changes: 5 additions & 0 deletions app/controllers/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export default Ember.Controller.extend({
this.myCrates = [];
this.myFollowing = [];
this.myFeed = [];
this.myStats = 0;
},

visibleCrates: computed('myCreates', function() {
Expand All @@ -26,6 +27,10 @@ export default Ember.Controller.extend({
return this.get('myFollowing').slice(0, TO_SHOW);
}),

visibleStats: computed('myStats', function() {
Copy link
Contributor

@locks locks Jul 2, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was looking at the code, and this and the other computed that depend on arrays should probably be myArray.[].
I wouldn't block the PR on that, but just want to note so it gets addressed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused, I think myStats is an int? Am I misunderstanding something because that's very likely

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, wrong line 😅

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WHEW. Did i fix it right? 9719fed

return this.get('myStats');
}),

hasMoreCrates: computed('myCreates', function() {
return this.get('myCrates.length') > TO_SHOW;
}),
Expand Down
4 changes: 4 additions & 0 deletions app/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ export default DS.Model.extend({
avatar: DS.attr('string'),
url: DS.attr('string'),
kind: DS.attr('string'),

stats() {
return this.store.adapterFor('user').stats(this.get('id'));
},
});
10 changes: 8 additions & 2 deletions app/routes/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default Ember.Route.extend(AuthenticatedRoute, {
controller.set('fetchingFeed', true);
controller.set('myCrates', this.get('data.myCrates'));
controller.set('myFollowing', this.get('data.myFollowing'));
controller.set('myStats', this.get('data.myStats'));

if (!controller.get('loadingMore')) {
controller.set('myFeed', []);
Expand All @@ -30,9 +31,14 @@ export default Ember.Route.extend(AuthenticatedRoute, {
following: 1
});

let myStats = user.stats();

return Ember.RSVP.hash({
myCrates,
myFollowing
}).then((hash) => this.set('data', hash));
myFollowing,
myStats
}).then((hash) => {
this.set('data', hash);
});
}
});
15 changes: 15 additions & 0 deletions app/styles/me.scss
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,21 @@
}
}

#stats {
margin-left: auto;
padding: 10px;

span { margin-left: 10px; }
.num {
font-size: 30px;
font-weight: bold;
}
.downloads {
@include display-flex;
@include align-items(center);
}
}

.me-subheading {
@include display-flex;
.right {
Expand Down
8 changes: 8 additions & 0 deletions app/templates/dashboard.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@
<div id='crates-heading'>
{{svg-jar "dashboard"}}
<h1>My Dashboard</h1>
<div id="stats">
<div class='downloads'>
<img class="download" src="/assets/download.png"/>
<span class='num'>{{visibleStats.total_downloads}}</span>
<span class='desc small'>Total Downloads</span>
</div>
</div>
</div>


<div id='my-info'>
<div id='my-crate-lists' class='crate-lists'>
<div id='my-crates'>
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ pub fn middleware(app: Arc<App>) -> MiddlewareBuilder {
api_router.get("/categories/:category_id", C(category::show));
api_router.get("/category_slugs", C(category::slugs));
api_router.get("/users/:user_id", C(user::show));
api_router.get("/users/:user_id/stats", C(user::stats));
api_router.get("/teams/:team_id", C(user::show_team));
let api_router = Arc::new(R404(api_router));

Expand Down
44 changes: 44 additions & 0 deletions src/tests/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use cargo_registry::krate::EncodableCrate;
use cargo_registry::user::{User, NewUser, EncodableUser};
use cargo_registry::version::EncodableVersion;

use diesel::prelude::*;

#[derive(RustcDecodable)]
struct AuthResponse {
url: String,
Expand Down Expand Up @@ -206,6 +208,48 @@ fn following() {
bad_resp!(middle.call(req.with_query("page=0")));
}

#[test]
fn user_total_downloads() {
use diesel::update;

let (_b, app, middle) = ::app();
let u;
{
let conn = app.diesel_database.get().unwrap();

u = ::new_user("foo").create_or_update(&conn).unwrap();

let mut krate = ::CrateBuilder::new("foo_krate1", u.id).expect_build(&conn);
krate.downloads = 10;
update(&krate).set(&krate).execute(&*conn).unwrap();

let mut krate2 = ::CrateBuilder::new("foo_krate2", u.id).expect_build(&conn);
krate2.downloads = 20;
update(&krate2).set(&krate2).execute(&*conn).unwrap();

let another_user = ::new_user("bar").create_or_update(&conn).unwrap();

let mut another_krate = ::CrateBuilder::new("bar_krate1", another_user.id)
.expect_build(&conn);
another_krate.downloads = 2;
update(&another_krate)
.set(&another_krate)
.execute(&*conn)
.unwrap();
}

let mut req = ::req(app, Method::Get, &format!("/api/v1/users/{}/stats", u.id));
let mut response = ok_resp!(middle.call(&mut req));

#[derive(RustcDecodable)]
struct Response {
total_downloads: i64,
}
let response: Response = ::json(&mut response);
assert_eq!(response.total_downloads, 30);
assert!(response.total_downloads != 32);
}

#[test]
fn updating_existing_user_doesnt_change_api_token() {
let (_b, app, _middle) = ::app();
Expand Down
23 changes: 23 additions & 0 deletions src/user/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,26 @@ pub fn updates(req: &mut Request) -> CargoResult<Response> {
meta: Meta { more: more },
}))
}

/// Handles the `GET /users/:user_id/stats` route.
pub fn stats(req: &mut Request) -> CargoResult<Response> {
use diesel::expression::dsl::sum;
use owner::OwnerKind;

let user_id = &req.params()["user_id"].parse::<i32>().ok().unwrap();
let conn = req.db_conn()?;

let data = crate_owners::table
.inner_join(crates::table)
.filter(crate_owners::owner_id.eq(user_id).and(
crate_owners::owner_kind.eq(OwnerKind::User as i32),
))
.select(sum(crates::downloads))
.first::<i64>(&*conn)?;

#[derive(RustcEncodable)]
struct R {
total_downloads: i64,
}
Ok(req.json(&R { total_downloads: data }))
}