Skip to content

Instantly share code, notes, and snippets.

@JakubOboza
Created February 13, 2012 19:30
Show Gist options
  • Select an option

  • Save JakubOboza/1819367 to your computer and use it in GitHub Desktop.

Select an option

Save JakubOboza/1819367 to your computer and use it in GitHub Desktop.
require("should")
class ContentTypeValidator
constructor: (whitelist = ['text/plain']) ->
@whitelist = []
for content_type in whitelist
@whitelist.push(content_type.toLowerCase())
validate: (obj) =>
match = false
for header, value of obj.headers
if header.toLowerCase() == 'content-type'
for supported_content_type in @whitelist
if supported_content_type == value
match = true
if match == true
{
valid: true
}
else
{
valid: false
errors: "Content type not supported"
}
class Validator
constructor: (validators = []) ->
@validators = validators
validate: (obj) ->
errors = []
for validator in @validators
result = validator.validate(obj)
if not result.valid
errors.push(result.errors)
errors
class DummyValidator
validate: (obj) ->
{
valid: true
}
module.exports.Validator = Validator
module.exports.ContentTypeValidator = ContentTypeValidator
# specs
request_object = {
headers: {
"Content-Type": "text/plain",
"Lol" : "Srsly ?"
}
}
case_sensitive = {
headers: {
"conTent-type": "application/json",
"X-Powered-By": "Kuba"
}
}
text_plain_object = {
headers: {
"CoNtEnT-Type": "text/plain"
}
}
describe 'Validations', () ->
describe 'ContentTypeValidator', () ->
it "should validate text/plain content-type by default", () ->
validator = new ContentTypeValidator()
validator.validate(text_plain_object).valid.should.equal(true)
it 'should not validate request_object', () ->
validator = new ContentTypeValidator(['application/json'])
validator.validate(request_object).valid.should.equal(false)
validator.validate(request_object).errors.should.equal("Content type not supported")
it "should be valid case insensitive", () ->
validator = new ContentTypeValidator(['Application/json', 'application/xml'])
validator.validate(case_sensitive).valid.should.equal(true)
describe 'Validator', () ->
it "should validate request object", () ->
validator = new Validator([new ContentTypeValidator(['application/json']), new DummyValidator()])
validator.validate(request_object)[0].should.equal("Content type not supported")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment