IronJSとSomaを使ってJavaScriptからDBアクセスしてみる

JavaScriptからSomaを動かしてみようと思って試行錯誤。呼び出すには呼び出せたけどIronJSドキュメントがまだ少ないしAPIがよくわからないしでとても限定的。もう少しさくっとJSからCLRのオブジェクトが呼び出せるといいなぁ。

F#

open System
open System.Collections
open System.Collections.Generic
open Soma.Core
open IronJS
module IronJS = IronJS.Hosting.FSharp

let ctx = IronJS.createContext()
let env = ctx.Env

let print (box:IronJS.BoxedValue) =
Console.WriteLine(IronJS.TypeConverter.ToString(box))
let printDelegate = new Action<IronJS.BoxedValue>(print)
let printFunction = printDelegate |> Native.Utils.createFunction env (Some 1)
ctx |> IronJS.setGlobal "print" printFunction

let config =
{ new MsSqlConfig() with
member
this.ConnectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True" }
let db = PlainDb(config)
let query (sql:string) (condition:obj) =
match condition with
| :? IronJS.CommonObject as co -> db.Query(sql, new Hashtable(co.Members))
| _ -> db.Query(sql)

let queryDelegate = new Func<string, obj, IList<IDictionary>>(query)
let queryFunction = queryDelegate |> Native.Utils.createFunction env (Some 2)
ctx |> IronJS.setGlobal "query" queryFunction

let result = ctx |> IronJS.execute @"
var results = query('select * from Person where id = /*id*/0', {id:2});
print('取得件数 ' + results.Count);
"
Console.ReadKey() |> ignore

実行結果
LOG : select * from Person where id = 2
取得件数 1

下から4行目の
query('select * from Person where id = /*id*/0', {id:2});
という記述でJavaScriptからSQL発行してます。

型変換とかいろいろ課題は多い。