Skip to content

Commit

Permalink
first commit 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieudutour committed Mar 21, 2017
0 parents commit cb8edcf
Show file tree
Hide file tree
Showing 5 changed files with 171 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .editorconfig
@@ -0,0 +1,5 @@
root = true

[*]
indent_style = space
indent_size = 2
5 changes: 5 additions & 0 deletions .gitignore
@@ -0,0 +1,5 @@
pids
logs
npm-debug.log
node_modules
.vscode
20 changes: 20 additions & 0 deletions README.md
@@ -0,0 +1,20 @@
# sketch-module-fetch-polyfill

A [fetch](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) polyfill for sketch inspired by [unfetch](https://github.com/developit/unfetch).

## Installation

```bash
npm i -S sketch-module-fetch-polyfill
```

## Usage

```js
import fetch from 'sketch-module-fetch-polyfill'

fetch("https://google.com")
.then(response => response.text())
.then(text => console.log(text))
.catch(e => console.error(e))
```
110 changes: 110 additions & 0 deletions lib/index.js
@@ -0,0 +1,110 @@
/* globals NSHTTPURLResponse NSString NSASCIIStringEncoding MOPointer NSJSONSerialization coscript NSURL NSMutableURLRequest NSMutableData NSURLConnection */
var MochaJSDelegate = require('mocha-js-delegate')

function response (httpResponse, data) {
const keys = []
const all = []
const headers = {}
let header

for (var i = 0; i < httpResponse.allHeaderFields().allKeys().length; i++) {
const key = httpResponse.allHeaderFields().allKeys()[i].toLowerCase()
const value = httpResponse.allHeaderFields()[key]
keys.push(key)
all.push([key, value])
header = headers[key]
headers[key] = header ? `${header},${value}` : value
}

return {
ok: (httpResponse.statusCode() / 200 | 0) == 1, // 200-399
status: httpResponse.statusCode(),
statusText: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode()),
url: httpResponse.URL(),
clone: response.bind(this, httpResponse, data),
text () {
return new Promise((resolve, reject) => {
const str = NSString.alloc().initWithData_encoding(data, NSASCIIStringEncoding)
if (str) {
resolve(str)
} else {
reject(new Error("Couldn't parse body"))
}
})
},
json () {
return new Promise((resolve, reject) => {
const err = MOPointer.alloc().initWithValue(null)
const obj = NSJSONSerialization.JSONObjectWithData_options_error(data, 0, err)
if (obj) {
resolve(obj)
} else {
reject(err.value())
}
})
},
xml () {
// TODO https://developer.apple.com/reference/foundation/nsxmlparser
return Promise.reject('not implemented yet')
},
blob () {
return Promise.resolve(data)
},
headers: {
keys: () => keys,
entries: () => all,
get: n => headers[n.toLowerCase()],
has: n => n.toLowerCase() in headers
}
}
}

function fetch (urlString, options) {
options = options || {}
coscript.setShouldKeepAround(true)
return new Promise((resolve, reject) => {
const url = NSURL.alloc().initWithString_(urlString)
const request = NSMutableURLRequest.requestWithURL_(url)
request.setHTTPMethod(options.method || 'GET')

for (let i in options.headers) {
request.setValue_forHTTPHeaderField(options.headers[i], i)
}

if (options.body) {
request.setHTTPBody(data)
}

const data = NSMutableData.alloc().init()
let httpResponse

const connectionDelegate = new MochaJSDelegate({
'connectionDidFinishLoading:' (connection) {
coscript.setShouldKeepAround(false)
return resolve(response(httpResponse, data))
},
'connection:didReceiveResponse:' (connection, _httpResponse) {
httpResponse = _httpResponse
},
'connection:didFailWithError:' (connection, error) {
coscript.setShouldKeepAround(false)
return reject(error)
},
'connection:didReceiveData:' (connection, _data) {
data.appendData(_data)
}
})

NSURLConnection.alloc().initWithRequest_delegate_startImmediately(request, connectionDelegate.getClassInstance(), true)
})
}


// polyfill the global object
const commonjsGlobal = typeof global !== 'undefined'
? global
: this

commonjsGlobal.fetch = commonjsGlobal.fetch || fetch

module.exports = fetch
31 changes: 31 additions & 0 deletions package.json
@@ -0,0 +1,31 @@
{
"name": "sketch-module-fetch-polyfill",
"version": "0.1.0",
"description": "A fetch polyfill for sketch",
"main": "lib/index.js",
"dependencies": {
"mocha-js-delegate": "^0.1.1"
},
"devDependencies": {
"standard": "^8.6.0"
},
"scripts": {
"test": "standard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mathieudutour/sketch-module-fetch-polyfill.git"
},
"keywords": [
"sketch",
"module",
"fetch",
"polyfill"
],
"author": "Mathieu Dutour <mathieu@dutour.me> (http://mathieu.dutour.me/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mathieudutour/sketch-module-fetch-polyfill/issues"
},
"homepage": "https://github.com/mathieudutour/sketch-module-fetch-polyfill#readme"
}

0 comments on commit cb8edcf

Please sign in to comment.