diff --git a/core/server/models/post.js b/core/server/models/post.js index 4b590e71a3..2b6ec90e62 100644 --- a/core/server/models/post.js +++ b/core/server/models/post.js @@ -71,15 +71,26 @@ Post = GhostBookshelf.Model.extend({ // Look for a post with a matching slug, append an incrementing number if so checkIfSlugExists = function (slugToFind) { return Post.read({slug: slugToFind}).then(function (found) { + var trimSpace; + if (!found) { return when.resolve(slugToFind); } slugTryCount += 1; - // TODO: Bug out (when.reject) if over 10 tries or something? + // If this is the first time through, add the hyphen + if (slugTryCount === 2) { + slugToFind += '-'; + } else { + // Otherwise, trim the number off the end + trimSpace = -(String(slugTryCount - 1).length); + slugToFind = slugToFind.slice(0, trimSpace); + } - return checkIfSlugExists(slugToFind + '-' + slugTryCount); + slugToFind += slugTryCount; + + return checkIfSlugExists(slugToFind); }); }; diff --git a/core/test/unit/api_posts_spec.js b/core/test/unit/api_posts_spec.js index 1ac3648c33..4633b2986c 100644 --- a/core/test/unit/api_posts_spec.js +++ b/core/test/unit/api_posts_spec.js @@ -1,5 +1,7 @@ /*globals describe, beforeEach, it */ var _ = require("underscore"), + when = require('when'), + sequence = require('when/sequence'), should = require('should'), helpers = require('./helpers'), Models = require('../../server/models'); @@ -110,19 +112,34 @@ describe('Post Model', function () { content_raw: 'Test Content 1' }; - PostModel.add(newPost).then(function (createdPost) { + // Create 12 posts with the sametitle + sequence(_.times(12, function (i) { + return function () { + return PostModel.add({ + title: "Test Title", + content_raw: "Test Content " + (i+1) + }); + }; + })).then(function (createdPosts) { + // Should have created 12 posts + createdPosts.length.should.equal(12); - createdPost.get('slug').should.equal('test-title'); + // Should have unique slugs and contents + _(createdPosts).each(function (post, i) { + var num = i + 1; - newPost.content_raw = 'Test Content 2'; - return PostModel.add(newPost); - }).then(function (secondPost) { - - secondPost.get('slug').should.equal('test-title-2'); - secondPost.get('content_raw').should.equal("Test Content 2"); + // First one has normal title + if (num === 1) { + post.get('slug').should.equal('test-title'); + return; + } + + post.get('slug').should.equal('test-title-' + num); + post.get('content_raw').should.equal('Test Content ' + num); + }); done(); - }).then(null, done); + }).otherwise(done); });